Convert number to binary string with full padding?

I have a long variable in java and convert it to a binary string like

long var = 24; Long.toBinaryString (shaft);

Now it prints only 7 bits, but I need to display all 64 bits, i.e. all leading zeros, how can I achieve this?

The reason is because I need to iterate over each bit and perform the operation according to the status, is there a better way to do this?

+3
source share
6 answers

If you want to iterate over bits, you might be better off testing each bit without converting it to a string:

if ((val & (1L << bitPosition)) != 0)
    // etc

, , , :

string padding = "0000000000000000000000000000000000000000000000000000000000000000";
string result = padding + Long.toBinaryString(val);
result = result.substring(result.length() - 64, result.length());  // take the right-most 64 digits
+9

long. "i" "" "".

long i = 1024;
for(int n = 63; n >= 0; n--)
    System.out.println(n + ": " + ((i & (1L << n)) != 0));
+5

, , :

int i=0, thisbit;
mask = 1;
while (i++ < 64)
{
    thisbit = var & mask;
    // check thisbit here...
    //
    var = var >>> 1;
    mask*=2;
}
+1

@Robert. Long.numberOfLeadingZeros(long).

.

+1

This will work;

String s =  Long.toBinaryString(val);
while (s.length() < 64)
{
    s = "0" + s;
}

If you want to do this with a StringBuffer, then:

StringBuffer s =  new StringBuffer(Long.toBinaryString(val));
while (s.length() < 64)
{
    s.insert(0, "0");
}
String str = s.toString();
0
source

Source: https://habr.com/ru/post/1725616/


All Articles