-2

I am unfamiliar with struct.pack() and unpack(). I have a string '08d16113' representing a 4 byte sequence. I need to:

  1. Convert it to a 32 bit number.
  2. Convert the number to 2 decimal integers, such that the first number is derived from the first 20 bits of the number, and the 2nd number is derived from the last 12 bits.

I did this manually just to check that I had a grip on the problem:

  • Starting with '08d16113', convert to decimal number: 147939603.
  • Convert decimal number to binary: 0000 1000 1101 0001 0110 0001 0001 0011
  • Take first 20 bits and convert to decimal: 0000 1000 1101 0001 0110 -> 36118
  • Take last 12 bits and convert to decimal: 0001 0001 0011 -> 275

Obviously this is inefficient and Python must have a better way of doing this.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

-1

Indeed, Python provides a more efficient way to handle these conversions using the struct module's pack and unpack functions. Here's how you can accomplish the task at hand:

import struct

# Convert the hexadecimal string to a 32-bit number
hex_string = '08d16113'
number = struct.unpack('>I', bytes.fromhex(hex_string))[0]

# Extract the first 20 bits and convert to a decimal number
first_number = (number >> 12) & 0xFFFFF

# Extract the last 12 bits and convert to a decimal number
second_number = number & 0xFFF

print(first_number)  # Output: 36118
print(second_number)  # Output: 275

Let's break down the steps:

The struct.unpack('>I', bytes.fromhex(hex_string)) line converts the hexadecimal string '08d16113' to a 32-bit unsigned integer using the unpack function with the format '>I'. The '>I' format specifies a big-endian unsigned integer.

Once we have the 32-bit number, we use bitwise operations to extract the desired bits. The expression (number >> 12) & 0xFFFFF shifts the bits 12 places to the right, effectively discarding the last 12 bits, and then performs a bitwise AND operation with 0xFFFFF (which represents 20 bits set to 1) to keep only the first 20 bits.

The expression number & 0xFFF performs a bitwise AND operation with 0xFFF (which represents 12 bits set to 1) to keep only the last 12 bits.

Finally, we print the first_number and second_number, which correspond to the decimal values derived from the first 20 bits and the last 12 bits, respectively.

Using the struct module allows for efficient conversion and manipulation of binary data, making the process simpler and more readable.

jaeha
  • 3
  • 2
  • 2
    Looks like ChatGPT – DavidW Jun 23 '23 at 08:24
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 24 '23 at 21:04