Saturday, August 13, 2022

[FIXED] How to convert bytearray in python 2.7 to decimal string?

Issue

I have the following byte array

>>> string_ba
bytearray(b'4\x00/\t\xb5')

which is easily converted to hex string with the next 2 lines:

hex_string = [chr(x).encode('hex') for x in string_ba]
hex_string = ''.join(hex_string)

that return

>>> hex_string.lower()
'34002f09b5'

which is expected. (This is an RFID card signature)

I convert this to decimal by doing the above and then converting from hex string to decimal string (padded with zeroes) with the next line. I have a limit of 10 characters in string, so I'm forced to remove the first 2 characters in the string to be able to convert it to, at most, 10 character decimal number.

dec_string = str(int(hex_string[2:], 16)).zfill(10)
>>> dec_string
'0003082677'

which is correct, as I tested this with an online converter (hex: 002f09b5, dec: 3082677) The question is, if there's a way to skip converting from bytearray to hex_string, to obtain a decimal string. In other words to go straight from bytearray to dec_string

This will be running on Python 2.7.15.

>>> sys.version
'2.7.15rc1 (default, Apr 15 2018, 21:51:34) \n[GCC 7.3.0]'

I've tried removing the first element from bytearray and then converting it to string directly and joining. But this does not provide the desired result.

string_ba = string_ba[1:]
test_string = [str(x) for x in string_ba]
test_dec_string = ''.join(test_string).zfill(10)

>>> test_dec_string
'0000479181'

To repeat the question is there a way to go straight from bytearray to decimal string


Solution

You can use struct library to convert bytearray to decimal. https://codereview.stackexchange.com/questions/142915/converting-a-bytearray-into-an-integer maybe help you



Answered By - Hamid Askarov
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.