Home > Back-end >  Add zeros in front of a binary number
Add zeros in front of a binary number

Time:04-07

I have a file that looks like this and was computed with Python:

1.30000000e 02 1.00000100e 07  
1.60000000e 01 1.00000000e 04  
4.55000000e 02 1.11000111e 08  
5.60000000e 01 1.11000000e 05  

But I would like to obtain something like this:

130 010000010  
16 000010000  
455 111000111  
56 000111000  

The idea is that I would like to add zeros to obtain a fixed format of 9 bits. The Python code that I wrote gives me the binary numbers, but for further decoding I need these binary numbers to have 9 bits. I tried to obtain them in the desired format from Python, but I was not able to do that.

Python code until now:

#!/usr/bin/env python3

import numpy as np
from numpy import genfromtxt
import os

day = os.environ.get('day')
Array = genfromtxt("SUC_diffzeros_" str(day) ".csv")
final = np.zeros(len(Array))

def decimaltobinary(x):
    for i in range(len(x)):
        final[i] = "{0:09b}".format(x[i])
        print(final)
    var = np.column_stack([Array, final])
    np.savetxt("SUC_diffzeros_" str(day) ".csv", var, fmt='%.8e')

if __name__ == '__main__':
    val = Array.astype(int)
    decimaltobinary(val)

I am running it as a Shell Script because this is part of a bigger project that contains commands written in bash. So, I exported the variable that I needed from bash and imported it in Python. Then, in the "Array" I have some numbers that I want to convert to the binary format with 9 bits. I want then to save these binary numbers in the original file as a new column next to the original decimal numbers. The code above just gives me:

1.30000000e 02 1.00000100e 07  
1.60000000e 01 1.00000000e 04  
4.55000000e 02 1.11000111e 08  
5.60000000e 01 1.11000000e 05  

The input file "SUC_diffzeros_" str(day) ".csv" contains 4 numbers (ex: 2 10 255 46). I want to take these numbers and convert them to binary. After that I want to add zeros in front of them in order to make each of these to have 9 digits, even though they start with 0. I was trying to convert them to strings in order to keep the 0s in front, because I saw that it doesn't work with int type.

I saw various examples on the internet, but all of these show just how to print these values. For example, if I print "final" after each iteration, it will look fine, as I wish. But then when I assign that value of "final[i]" it will get rid of the zeros in front.

I need that assignment because I want to write these values with 0s in front in a file, not just print them.

CodePudding user response:

Something like this?

for num in [
  # OP says the right column of the data is not there and should be ignored, so edited accordingly
  '1.30000000e 02',
  '1.60000000e 01',
  '4.55000000e 02',
  '5.60000000e 01'
]:
    f = float(num)
    n = int(f)
    print(f"{n} {n:09b}")

This takes the each string and interprets it as a float, then converts that float to an integer, and displays its decimal representation alongside the 9-bit binary representation.

CodePudding user response:

If you want to convert a decimal number into a 9-bit binary number then try this,

number = 16
def decimaltobinary(x):
    inttobin = format(x, '#010b')
    bintostr = inttobin[2:]
    if len(bintostr) < 9:
        bintostr = '0'   bintostr
    return bintostr

print(decimaltobinary(number))
  • Related