PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

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

 August 13, 2022     arrays, decimal, python, python-2.7, string     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing