开发者

Convert number to binary string with full padding?

I have a long variable in java and am converting it to a binary string, like

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

Now this prints only 7 bits, but I need to display all the 64 bits, i.e. all the leading zeros also, how can I ac开发者_如何转开发hieve this?

The reason is I need to iterate through each bit and perform an operation according to the status, is there a better way to do it?


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

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

But, if you truly want a binary string, this is the easiest way to left-pad it with zeros:

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


You can use binary operators to access the individual bits of an long. The following code prints the individual bits of "i" as "true" or "false".

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


Not sure, but I think it should go like this:

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


I would add little modification on @Robert's answer. Instead of declaring padding variable here, use Long.numberOfLeadingZeros(long).

Actually internally it make use of shift operators only.


Yes, see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html for information on bitwise operations.

Otherwise use the Formatter: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html


This will work;

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

If you want to do this with a StringBuffer, so;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜