Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2,3 Convert Integer to "bytes" Cleanly

Tags:

python

The shortest ways I have found are:

n = 5  # Python 2. s = str(n) i = int(s)  # Python 3. s = bytes(str(n), "ascii") i = int(s) 

I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible.

Is there a shorter, cleaner way that I have missed? I currently make a lambda expression to fix it with a new function, but maybe that's unnecessary.

like image 318
imallett Avatar asked Dec 26 '12 17:12

imallett


People also ask

How do you convert int to byte in Python?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

How do you convert int to byte value?

Java Integer byteValue() MethodThe byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte). Also, remember this method does override byteValue() method of the Number class.

Can we typecast int to byte?

Yes you do. For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast. you do not actually need to cast to byte in your assignment.

What does byte () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.


2 Answers

Answer 1:

To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encode method. If you don't supply an encoding parameter 'ascii' is used, which will always be good enough for numeric digits.

s = str(n).encode() 
  • Python 2: http://ideone.com/Y05zVY
  • Python 3: http://ideone.com/XqFyOj

In Python 2 str(n) already produces bytes; the encode will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.


Answer 2:

Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I'll answer that question too. If you want to convert 10 to b'10' use the answer above, but if you want to convert 10 to b'\x0a\x00\x00\x00' then keep reading.

The struct module was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack. There's a format parameter fmt that determines which conversion it should perform. For a 4-byte integer, that would be i for signed numbers or I for unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.

import struct s = struct.pack('<i', 5) # b'\x05\x00\x00\x00' 
like image 162
Mark Ransom Avatar answered Oct 17 '22 09:10

Mark Ransom


You can use the struct's pack:

In [11]: struct.pack(">I", 1) Out[11]: '\x00\x00\x00\x01' 

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1) Out[12]: '\x01\x00'  In [13]: struct.pack("B", 1) Out[13]: '\x01' 

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

like image 45
Andy Hayden Avatar answered Oct 17 '22 08:10

Andy Hayden