3

I want to create a binary.bin file from a binary.txt file.

The .txt file only contains ones and zeroes. I found a way of converting hexadecimal into .bin using the xxd linux function but can not find a method for converting .txt zeroes and ones to hexadecimal that can be applied with the xxd tool to make a .bin file.

I tried to make a script for converting the binary.txt to a hexademical.txt which could then be used with xxd in linux, but this seems to be not working... The problem is that the python script outputs some other hexadecimal than the xxd hexdump function in linux.

In short... I tried this using xxd with a .bin file:

.bin > hex > .bin (works)

I cannot make .bin file from:

hex (python) > .bin (does not work)

# converts binary.txt > hex .txt
# for example: 01000110 outputs 0xf42ae

data1 = open('13bitSystem_1row.txt', 'r')
data2 = open("hex_" + data1.name, 'w')

# () specifies number of decimal characters used, remove number to run whole file
file = data1.read()

decimal_representation = int(file)
hexadecimal_string = hex(decimal_representation)

data2.write(hexadecimal_string)

data1.close()
data2.close()

For example: The binary sequence .txt 01000110 outputs 4F in xxd but 0xf42ae in python

  • Are you sure about those numbers? If `01000110` is binary then it is 70 in base 10, whereas `0xf42ae` is `1000110` in base 10. – tomjn Jun 02 '21 at 13:30
  • @tomjn Yeah, so the python script probably interprets the data as decimal instead of a binary sequence? This could explain 0xf4697 instead of 4F? Do you have a clue on how I could interpret a .txt file as binary instead of decimal to get 4F? Thanks – Tigge Nilsson Jun 02 '21 at 13:36
  • 1
    If it is meant to be binary then you should do `decimal_representation = int(file, base=2)` – tomjn Jun 02 '21 at 13:39
  • what tomjn said. `int` is converting the file from decimal, which is not what you want. `base=2` will convert it from binary (`base` `2`), which is definitely what you want. – Wezl Jun 02 '21 at 13:41
  • I got it now, thank you very much! – Tigge Nilsson Jun 02 '21 at 14:00

0 Answers0