0
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.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Shubham Agrawal
  • 1,252
  • 12
  • 29

3 Answers3

0

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

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • But I want my output to be like `\x00\x00\xf3`. Same as your output but in case of 0x0, I want it as \x00. Please help me how to achieve thus – Shubham Agrawal Nov 01 '19 at 05:31
0

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"

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

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)
Shubham Agrawal
  • 1,252
  • 12
  • 29