Python bytearray to integer

Convert Bytes to Int in Python

In this post, we will see how to convert Bytes to Int in Python.

Normally, the data is stored in the storage in bytes format. In this article, we will discuss how we can convert data given as bytes to integer or int data types in python. For this, we will use the int.from_bytes() method.

How to Convert Bytes to Int in Python?

We will convert bytes to int using the int.from_bytes() method. The syntax for the from_bytes() method is as follows.

  • The parameter bytes takes the bytes object that has to be converted to int as the input argument.
  • The byteorder parameter is used to define the byte order of the bytes object that is passed as the first input argument.
    • If “ big ” is given as an input argument to the byteorder parameter, the first byte from the beginning of the bytes object is considered to be the most significant byte.
    • If “ little ” is given as an input argument to the byteorder parameter, the first byte from the end of the bytes object is considered to be the most significant byte.
    • To use the byte order of the machine on which the program is being run, you can use the sys.byteorder attribute using the sys module.

    How to Convert Bytes to Signed Int in Python?

    To convert the bytes object to a signed int, we will set the parameter signed to True in the from_bytes() method. To observe this, let us first create a bytes object from an integer using the int.to_bytes() method. The to_bytes() method takes the integer value as the first input argument, the length of the output bytes object as the second input argument and the byteorder as the third input argument. After execution, it returns the bytes object. Then we can convert the bytes object to int using the from_bytes() method as shown below.

    Источник

    How To Convert A Python ByteArray Object To String, Bytes, Int, List With Examples

    In the previous article, I have told you what is python bytearray object, how to create, modify, and append it. In this article, I will show you some examples about how to convert a bytearray object to string, bytes, integer, and list object in python source code.

    1. Python ByteArray To String Example.

    1.1 Example 1.

    1. In Python, you can convert a bytearray object to a string using the decode() method.
    2. The decode() method takes an optional argument that specifies the character encoding of the bytearray .
    3. If no argument is provided, the default encoding is ‘utf-8’ .
    4. Here’s an example of how to convert a bytearray to a string:
    # Create a bytearray from a string my_string = "hello world" my_bytearray = bytearray(my_string, "utf-8") # Print the bytearray object on the console print(my_bytearray) # Change the first byte ascii code to 72 which represents character H. my_bytearray[0] = 72 # Convert the bytearray to a string my_string = my_bytearray.decode() # Print the final string print(my_string) # Output: hello world
    bytearray(b'hello world') Hello world >>>

    1.2 Example 2.

    1. If the bytearray was created with a different encoding than the default, you can specify the correct encoding as an argument to the decode() method.
    2. Here’s an example of how to do this:
    # Create a bytearray from a string with a different encoding my_string = "你好, world" # Use GB2312 text encoding. my_bytearray = bytearray(my_string, "GB2312") # Print the bytearray object on the console print(my_bytearray) # Convert the bytearray to a string with the correct encoding my_string = my_bytearray.decode("GB2312") # Print the final string print(my_string)
    bytearray(b'\xc4\xe3\xba\xc3, world') 你好, world

    2. Python ByteArray To Bytes Example.

    1. In Python, you can convert a bytearray object to bytes using the bytes() function.
    2. The bytes() function returns an immutable bytes object that contains the same elements as the bytearray .
    3. Here’s an example of how to convert a bytearray to bytes:
    # Create a bytearray from a string my_string = "hello world" my_bytearray = bytearray(my_string, "utf-8") # Convert the bytearray to bytes my_bytes = bytes(my_bytearray) # Print the final bytes object print(my_bytes) # Output: b'hello world'
    # Create a bytes object from a bytearray my_bytearray = bytearray(b"hello world") my_bytes = bytes(my_bytearray) # Access an individual element of the bytes object print(my_bytes[0]) # Output: 104

    3. Python ByteArray To Integer Example.

    1. In Python, you can convert a bytearray object to an integer using the int.from_bytes() method.
    2. The int.from_bytes() method takes two arguments: the bytearray object to convert, and the byte order of the integer representation.
    3. Here’s an example of how to convert a bytearray to an integer:
    # Create a bytearray from an integer my_int = 1000 my_bytearray = my_int.to_bytes(2, byteorder="big") # Convert the bytearray to an integer my_int = int.from_bytes(my_bytearray, byteorder="big") # Print the final integer print(my_int) # Output: 1000
    # Create a bytearray from an integer with little-endian byte order my_int = 1000 my_bytearray = my_int.to_bytes(2, byteorder="little") # Convert the bytearray to an integer with little-endian byte order my_int = int.from_bytes(my_bytearray, byteorder="little") # Print the final integer print(my_int) # Output: 1000

    4. Python ByteArray To List Example.

    1. In Python, you can convert a bytearray object to a list of integers using a list comprehension.
    2. The list comprehension iterates over each element of the bytearray and converts it to an integer.
    3. Here’s an example of how to convert a bytearray to a list:
    # Create a bytearray from a string my_string = "hello world" my_bytearray = bytearray(my_string, "utf-8") # Convert the bytearray to a list of integers my_list = [int(byte) for byte in my_bytearray] # Print the final list print(my_list) # Output: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
    # Create a bytearray from a string my_string = "hello world" my_bytearray = bytearray(my_string, "utf-8") # Convert the bytearray to a list of characters my_list = [chr(byte) for byte in my_bytearray] # Print the final list print(my_list) # Output: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

    Источник

    Converting a bytearray into an integer

    I am working on a program to decode MMS PDU files. They are binary files and I am reading them byte by byte and decoding each header value as I come to it. One header value is the Date, and it’s represented as follows (in hex):

    0x85 is the «Date» header, 0x04 is the data length (4 bytes) and the 4 following bytes represent the date (timestamp). I have code to read those 4 bytes and return it to me as a bytearray :

    Apparently \x57 is a W and \x49 is an I . In order to parse this as a date, I need to convert it to an int. These bytes represent the timestamp 1474470473 (or 0x57E2A249 ). I have code to convert this byte array into an int, but there has got be a better way to do it than the way I came up with.

    timestamp = int(''.join(map(hex, byte_range)).replace('0x', ''), 16) value = datetime.fromtimestamp(timestamp) 

    That is, I am converting every byte to a string (like «0x57» ), joining them together, removing the «0x»s , then reading that string as a base 16 value. This works, but it seems a little too convoluted. I then realized that I could replace the join / map with binascii.hexlify , so now my code is:

    timestamp = int(binascii.hexlify(byte_range), 16) value = datetime.fromtimestamp(timestamp) 

    Like I said, this code works, but I just feel there’s a better way to do this than to convert the bytearray into a string and then parse that string back as a base-16 int.

    Источник

    Convert Bytes to Int in Python 2.7 and 3.x

    Craving a more dynamic learning experience? we’ve crafted a comprehensive YouTube video complementing this article embedded at the end of this page!

    Convert Bytes to Int in Python 2.7 and 3.x

    Bytes data type has the value with a range from 0 to 255 (0x00 to 0xFF). One byte has 8 bits; that’s why its maximum value is 0xFF. In some circumstances, you need to convert bytes or bytes array to integers for further data processing. This short article introduces methods to convert byte to int in Python, like the struct.unpack method in Python 2.7 and int.from_bytes() in Python 3.x.

    Python 2.7 Bytes Data Type

    There is no built-in bytes data type in Python 2.7 version. Keyword byte is identical to str .

    bytearray is used to define a bytes or byte array object.

    >>> byteExample1 = bytearray([1]) >>> byteExample1 bytearray(b'\x01') >>> byteExample2 = bytearray([1,2,3]) >>> byteExample2 bytearray(b'\x01\x02\x03') 

    Convert Byte to Int in Python 2.7

    Python internal module struct could convert binary data (bytes) to integers. It could convert bytes or actually strings in Python 2.7 and integers in a bidirectional way.

    struct.unpack(fmt, string)  Convert the string according to the given format `fmt` to integers. The result is a tuple even if there is only one item inside. 

    struct Examples: Convert Byte to Int in Python 2.7

    import struct testBytes = b'\x00\x01\x00\x02' testResult = struct.unpack('>HH', testBytes) print testResult 
    1. > indicates the binary data is big-endian , or in other words, the data is ordered from the big end (most significant bit). For example, \x00\0x1 means \x00 is the high byte, and \x01 is the low byte.
    2. HH means there are two objects of H types in the bytes string. H represents an unsigned short integer that takes 2 bytes.

    You could get different results from the same string if the assigned data format is different.

    >>> testResult = struct.unpack(', testBytes) >>> testResult (256, 512) 
    >>> testResult = struct.unpack(', testBytes) >>> testResult (0, 1, 0, 2) 

    B means the data is unsigned char taking 1 byte. Hence, \x00\x01\x00\x02 will be converted to 4 values of unsigned char , but not 2 values of unsigned short anymore.

    The data length represented by the format string shall be the same as the given data; otherwise, it reports an error.

    >>> testResult = struct.unpack(', b'\x00\x01\x00\x02')  Traceback (most recent call last):  File "", line 1, in module>  testResult = struct.unpack(', b'\x00\x01\x00\x02') error: unpack requires a string argument of length 3 

    You could check the struct module’s official document to get more information on format strings.

    Python 3 Bytes Data Type

    bytes is a built-in data type in Python 3; therefore, you could define bytes directly using the bytes keyword.

    >>> testByte = bytes(18) >>> type(testByte) class 'bytes'> 

    You could also directly define a bytes or bytes array like below.

    >>> testBytes = b'\x01\x21\31\41' >>> type(testBytes) class 'bytes'> 

    Convert Bytes to Int in Python 3

    Besides the struct module as already introduced in Python 2.7, you could also use a new Python 3 built-in int method to do the bytes-to-integers conversions, that is, the int.from_bytes() method.

    int.from_bytes() Examples: Convert Byte to Int

    >>> testBytes = b'\xF1\x10' >>> int.from_bytes(testBytes, byteorder='big') 61712 

    The byteorder option is similar to struct.unpack() format byte order definition.

    int.from_bytes() has a third option signed to assign the integer type to be signed or unsigned .

    >>> testBytes = b'\xF1\x10' >>> int.from_bytes(testBytes, byteorder='big', signed=True) -3824 

    Use [] When Bytes Is unsigned char

    If the format of data has the format of unsigned char containing only one byte, you could directly use object index to access and get the integer of the data.

    >>> testBytes = b'\xF1\x10' >>> testBytes[0] 241 >>> testBytes[1] 16 

    Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

    Related Article — Python Bytes

    Источник

    Читайте также:  Сумма всех чисел массива javascript
Оцените статью