Convert to Binary and Keep Leading Zeros

Convert to binary and keep leading zeros

Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'

Converting a binary formatted string (with leading zeros) to an integer and back again

You can append a flag bit after the MSB to protect all the leading zeros.

Step 1: Conversion

Add a single "flag" bit at the end and convert your bit string.

In [6]: converted_str = '001000100010001011100011001000'

In [9]: num = int('1' + converted_str, 2)

In [10]: num
Out[10]: 1216919752

Step 2: Re-conversion

Use the format method to convert your number back to a bit string, while stripping off the first "flag" bit.

In [12]: reconverted_str = format(num, 'b')[1:]

In [13]: reconverted_str
Out[13]: '001000100010001011100011001000'

Integer to BinaryString removes leading zero in Java

its suppose to be 010010....

not really, integer type have made up from 32 bits, so it should be:

000000000000000000000000010010, java is not going to print that information, left zeros are in this case not relevant for the magnitude of that number..

so you need to append the leading zeros by yourself, since that method is returning a string you can format that:

String.format("%32s", Integer.toBinaryString(18)).replace(' ', '0')

or in your case using 6 bits

String.format("%6s", Integer.toBinaryString(18)).replace(' ', '0')

How to convert int64 to binary and keep leading zeros in golang?

You can format directly as binary with padding:

fmt.Printf("%064b\n", n)

See https://play.golang.org/p/JHCgyPMKDG

Way to add leading zeroes to binary string in JavaScript

It's as simple as

var n = num.toString(2);
n = "00000000".substr(n.length) + n;

Converting from hex to binary without losing leading 0's python

I don't think there is a way to keep those leading zeros by default.

Each hex digit translates to 4 binary digits, so the length of the new string should be exactly 4 times the size of the original.

h_size = len(h) * 4

Then, you can use .zfill to fill in zeros to the size you want:

h = ( bin(int(h, 16))[2:] ).zfill(h_size)


Related Topics



Leave a reply



Submit