Chinna
Chinna

Reputation: 3992

python3: converting interger value(2byte) to two individual bytes in byte array

I have following code which try to convert an integer value to two individual bytes in a bytearray.

value = 13183
print("Initial value: ", value)
val_msb = (value >> 8) & 0xFF
val_lsb = value & 0xFF
print("Value MSB:", val_msb, "Value LSB:", val_lsb)

val_arr = bytearray(2);
val_arr[0] = val_msb
val_arr[1] = val_lsb
print("Byte array:", val_arr)

Getting following output which is not matching with the expectation.

Initial value:  13183
Value MSB: 51 Value LSB: 127
Byte array: bytearray(b'3\x7f')

I expect it to produce final bytearray as Byte array: bytearray(b'x33\x7f')

Upvotes: 0

Views: 115

Answers (1)

Jim Danner
Jim Danner

Reputation: 545

The character ’3’ has character code 51 (or 0x33). So what you’re seeing there, the 3, is not the numeric value but the character into which it is translated. If you make your last command

print(list(val_arr))

you can see that the values are correct.

Upvotes: 1

Related Questions