I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.
How can I do this?
You can convert a string to a 32-bit signed integer with the int function:
string = "1234"
i = int(string) # i is a 32-bit integer
If the string does not represent an integer, you'll get a ValueError exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type long instead.
You can then convert it to other widths and signednesses with some simple math:
s8 = (i + 2**7) % 2**8 - 2**7 # convert to signed 8-bit
u8 = i % 2**8 # convert to unsigned 8-bit
s16 = (i + 2**15) % 2**16 - 2**15 # convert to signed 16-bit
u16 = i % 2**16 # convert to unsigned 16-bit
s32 = (i + 2**31) % 2**32 - 2**31 # convert to signed 32-bit
u32 = i % 2**32 # convert to unsigned 32-bit
s64 = (i + 2**63) % 2**64 - 2**63 # convert to signed 64-bit
u64 = i % 2**64 # convert to unsigned 64-bit
You can convert strings to floating point with the float function:
f = float("3.14159")
Python floats are what other languages refer to as double, i.e. they are 64-bits. There are no 32-bit floats in Python.
Python only has a single int type. To convert a string to an int, use int() like this:
>>> str = '123'
>>> num = int(str)
>>> num
123
Edit: Also to convert to float, use float() in the exact same way.
The following types -- for the most part -- don't exist in Python in the first place. In Python, strings are converted to ints, longs or floats, because that's all there is.
You're asking for conversions that aren't relevant to Python in the first place. Here's the list of types you asked for and their Python equivalent.
unsigned and signed int 8 bits, int
unsigned and signed int 16 bits, int
unsigned and signed int 32 bits, unsigned: long, signed int
unsigned and signed int 64 bits, long
double, float
float, float
string, this is what you had to begin with
I don't know what the following are, so I don't know a Python equivalent.
unsigned and signed 8 bit,
unsigned and signed 16 bit,
unsigned and signed 32 bit,
unsigned and signed 64 bit.
You already have all the conversions that matter: int(), long() and float().
I don't think this can necessarily be answered well without more information. As others have said, there are only int and long for integers in python -- the language doesn't adhere to the bit-width and signedness archetypes of lower-level programming languages.
If you're operating completely within python, then you're probably asking the wrong question. There's likely a better way to do what you need.
If you are interoperating with, for instance, C code, or over the network, then there are ways to do this, and it looks like the answer to your previous posting covered that avenue pretty handily.
I just now had a problem where I had a value passed as a 16 bit signed twos complement number from modbus.
I needed to convert this to a signed number.
I ended up writing this, which seems to work fine.
# convert a 32 bit (prob) integer as though it was
# a 16 bit 2's complement signed one
def conv_s16(i):
if (i & 0x8000):
s16 = -(((~i) & 0xFFFF) + 1)
else:
s16 = i
return s16
Related
I am working with byte (receiving data from IOT devices)
There are a few terms that I dont understand.
For example:
If the document mentions the data size of 2 (signed int). Then for the next 2 value I should do:
((byteArray[0] << 8) + byteArray[1])
I actually dont get why we should do it. Anyway I need to know the resolve for :
4 signed int
2 (signed int MSB) + 1 (unsigned int, decimal part)
==========================================
For example:
If the list's first value is 0x01 -> the next 2 value is the data we want but it is 2 (signed int). My code handle for that is :
data = bytearray.fromhex(input)
#data size of 2 (signed int)
if data[0].to_bytes(1,'big') == b'\x01':
wanttedData = ((input[1] << 8) + input[2])
#data size of 4 (signed int)
The struct package is a good way to convert byte data into various types. You need to know the endianness of the data. From your example the data appears to be big endian.
For example, if the data is:
byteArray[0] is an 8 bit signed integer
byteArray[1:2] is a 16 bit signed integer
byteArray[3:6] is a 32 bit unsigned integer
then you can decode the data using a format of ">bhI" (the > indicates big-endian, and each letter corresponds to each data type), and you can extract the three values with:
import struct
byte_string = b'\x02\x03\x05\x12\x34\x56\xff'
val0, val1, val2 = struct.Struct(">bhI").unpack_from(byte_string)
print(hex(val0), hex(val1), hex(val2)) # prints 0x2 0x305 0x123456ff
I need to cast bit sequences of arbitrary length to signed or unsigned integers. Those sequences are represented as strings. for example, I have to cast '001100100110100101110011001010' to an unsigned integer and '10000000' to a signed integer.
I used int('10000000', 2), but I haven't been able to find an intuitive approach to switch between signed/unsigned. Is there a straight-forward way to do this in Python?
I have a hex string, for instance: 0xb69958096aff3148
And I want to convert this to a signed integer like: -5289099489896877752
In Python, if I use the int() function on above hex number, it returns me a positive value as shown below:
>>> int(0xb69958096aff3148)
13157644583812673864L
However, if I use the "Hex" to "Dec" feature on Windows Calculator, I get the value as: -5289099489896877752
And I need the above signed representation.
For 32-bit numbers, as I understand, we could do the following:
struct.unpack('>i', s)
How can I do it for 64-bit integers?
Thanks.
If you want to convert it to 64-bit signed integer then you can still use struct and pack it as unsigned integer ('Q'), then unpack as signed ('q'):
>>> struct.unpack('<q', struct.pack('<Q', int('0xb69958096aff3148', 16)))
(-5289099489896877752,)
I would recommend the bitstring package available through conda or pip.
from bitstring import BitArray
b = BitArray('0xb69958096aff3148')
b.int
# returns
-5289099489896877752
Want the unsigned int?:
b.uint
# returns:
13157644583812673864
You could do a 64-bit version of this, for example:
def signed_int(h):
x = int(h, 16)
if x > 0x7FFFFFFFFFFFFFFF:
x -= 0x10000000000000000
return x
print(signed_int('0xb69958096aff3148'))
Output
-5289099489896877752
I am faced with a problem in Python and I think I don't understand how signed numbers are handled in Python. My logic works in Java where everything is signed so need some help in Python.
I have some bytes that are coded in HEX and I need to decode them and interpret them to numbers. The protocol are defined.
Say the input may look like:
raw = '016402570389FFCF008F1205DB2206CA'
And I decode like this:
bin_bytes = binascii.a2b_hex(raw)
lsb = bin_bytes[5] & 0xff
msb = bin_bytes[6] << 8
aNumber = int(lsb | msb)
print(" X: " + str(aNumber / 4000.0))
After dividing by 4000.0, X can be in a range of -0.000025 to +0.25.
This logic works when X is in positive range. When X is expected
to be negative, I am getting back a positive number.
I think I am not handling "msb" correctly when it is a signed number.
How should I handlehandle negative signed number in
Python?
Any tips much appreciated.
You can use Python's struct module to convert the byte string to integers. It takes care of endianness and sign extension for you. I guess you are trying to interpret this 16-byte string as 8 2-byte signed integers, in big-endian byte order. The format string for this is '>8h. The > character tells Python to interpret the string as big endian, 8 means 8 of the following data type, and h means signed short integers.
import struct
nums = struct.unpack('>8h', bin_bytes)
Now nums is a tuple of integers that you can process further.
I'm not quite sure if your data is little or big endian. If it is little-endian, you can use < to indicate that in the struct.unpack format string.
Input = 'FFFF' # 4 ASCII F's
desired result ... -1 as an integer
code tried:
hexstring = 'FFFF'
result = (int(hexstring,16))
print result #65535
Result: 65535
Nothing that I have tried seems to recognized that a 'FFFF' is a representation of a negative number.
Python converts FFFF at 'face value', to decimal 65535
input = 'FFFF'
val = int(input,16) # is 65535
You want it interpreted as a 16-bit signed number.
The code below will take the lower 16 bits of any number, and 'sign-extend', i.e. interpret
as a 16-bit signed value and deliver the corresponding integer
val16 = ((val+0x8000)&0xFFFF) - 0x8000
This is easily generalized
def sxtn( x, bits ):
h= 1<<(bits-1)
m = (1<<bits)-1
return ((x+h) & m)-h
In a language like C, 'FFFF' can be interpreted as either a signed (-1) or unsigned (65535) value. You can use Python's struct module to force the interpretation that you're wanting.
Note that there may be endianness issues that the code below makes no attempt to deal with, and it doesn't handle data that's more than 16-bits long, so you'll need to adapt if either of those cases are in effect for you.
import struct
input = 'FFFF'
# first, convert to an integer. Python's going to treat it as an unsigned value.
unsignedVal = int(input, 16)
assert(65535 == unsignedVal)
# pack that value into a format that the struct module can work with, as an
# unsigned short integer
packed = struct.pack('H', unsignedVal)
assert('\xff\xff' == packed)
# ..then UNpack it as a signed short integer
signedVal = struct.unpack('h', packed)[0]
assert(-1 == signedVal)