简体   繁体   中英

Binary String data to Hexadecimal in python

binaryValue= '000000000000000011110011'

I want to segregate 8 characters and convert that 8 bits to hexadecimal format as the above will have a value of '0x000x000xf3' .

I want this value to be printed via python as '\x00\x00\xf3' . Please let me know how to achieve this using python. And please let me know what will happen if there is '\n' after every binaryValue string at the end of it. How to achieve this also.

you can do something like:

inputStr = '000000000000000011110011'
n = 8
listOfBytes = [inputStr[i:i+n] for i in range(0, len(inputStr), n)]
for i in listOfBytes: 
    print(hex(int(i, 2)))

output_:

0x0 0x0 0xf3

Well you can do this:

b = '000000000000000011110011'
h = '\\' + '\\'.join('x' + hex(int(b[i:i + 8], 2)).split('x')[1].zfill(2) for i in range(0, len(b), 8))
print(h) # This will print \x00\x00\xf3

Breaking it down as a longer loop to make it more readable:

b = '000000000000000011110011'
h = ''
for i in range(0, len(b), 8): # Same as you did
    temp = hex(int(b[i:i + 8], 2)) # Same as you did
    temp = temp.split('x')[1] # to get the last part after x
    temp = temp.zfill(2) # add leading zeros if needed
    h += '\\x' + temp # adding the \x back
print(h) # This will print \x00\x00\xf3

I'm guessing you have to use that as unicode and/or convert it to something else? If so, see the answers here: Python: unescape "\xXX"

The correct answer which I figured out is:

binaryString = '000000000000000011110011'
hexString = ''
for i in range(0, len(binaryString), 8):
    if len(hex(int(binaryString[i:i + 8], 2))) == 3:
        tempString = hex(int(binaryString[i:i + 8], 2)).replace("0x", "\\x")
        hexString += "0" + tempString
    else:
        hexString += hex(int(binaryString[i:i + 8], 2)).replace("0x", "\\x")

print(hexString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM