Home > Software design >  Converting Hexa to Binary from list
Converting Hexa to Binary from list

Time:11-30

Im trying to open list with values and their hexa data and convert each line to only binary value (with small mask).

For example in my txt file I have:

DATA0 = 0x413e960d
DATA1 = 0x1c1c81c7
DATA2 = 0xa0000000
(32 Bits)

I want the output to be:

000000000000000001000001001111101001011000001101
000000000000000000011100000111001000000111000111
000000000000000010100000000000000000000000000000
(48 Bits)

I want to write those values in a new file, In my code for some reason, it skips the first value conversion, can you assist me with understanding why?

Code:

with open(input,'r') as r, open(output,'w') as w:
        #lines = r.readlines()
        
        for line in r:
            # if not line.startswith('#'):
            if line.startswith('DATA'):
                #print(line)
                new_line = line.rsplit("=")[1]
                new_line.strip()
                w.writelines(new_line)
                w.writelines(new_line   str( bin(int(new_line, 16))[2:] ).zfill(48))

I have also tried this conversion : (Last line)

        w.writelines(new_line   str('{:048b}'.format(int(new_line.strip(), 16))))

CodePudding user response:

You're writing your hex values twice with inconsitent line breaks, but overall I see all values being converted. Try to simplify your code:

with open("file.txt",'r') as r, open("output.txt",'w') as w:
    for line in r:
        if line.startswith('DATA'):
            hex_val = line.rsplit("=")[1].strip()
            w.writelines(f"{hex_val}:\n{bin(int(hex_val, 16))[2:].zfill(48)}\n\n")

Output:

0x413e960d:
000000000000000001000001001111101001011000001101

0x1c1c81c7:
000000000000000000011100000111001000000111000111

0xa0000000:
000000000000000010100000000000000000000000000000

CodePudding user response:

You forget to strip "\n" from line

with open("input.txt",'r') as r, open("output.txt",'w') as w:
    for line in r:
        line_without_white_characters_including_next_line = ''.join(line.split()) # removes whitespaces and \n
        if line_without_white_characters_including_next_line.startswith('DATA'):
            new_line = line_without_white_characters_including_next_line.split("=")[1]
            w.writelines(str( bin(int(new_line, 16))[2:] ).zfill(48))
            w.writelines("\n") # need to write next line so values are not next to each other

My output:

000000000000000001000001001111101001011000001101
000000000000000000011100000111001000000111000111
000000000000000010100000000000000000000000000000
  • Related