Number of bits used in long - java
I want to know the number of bits really used in the long datatype in Java. For instance:
long time = System.currentTimeMillis();
System.out.println(java.lang.Long.toHexString(time));
Output:
12c95165393Here you can see it only has 11 hex digits which means only 44 bits out of 64 are utilized. 10 bits are still un-utilized. Is there a 开发者_如何学Cway to know at runtime how many bits are used OR to pad the remaining bits ?
Try Long.numberOfLeadingZeros():
long time = System.currentTimeMillis();
System.out.println(Long.numberOfLeadingZeros(time));
For used bits:
Long.SIZE - Long.numberOfLeadingZeros(time)
According to the API for 'toHexString', the leading zeros are stripped. http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Long.html#toHexString(long)
Therefore, you can't answer this question with the toHexString method.
You can format it with padding using String.format
:
System.out.println(String.format("%016x", time));
If you want to know how many of the leading bits are unset you can either check the bits individually or you can right shift the number (with >>>
, not >>
) until it's zero.
There are just 11 hex digits in your example, because toHexString doesn't output leading zeroes.
Code:
String minBin=Long.toBinaryString(Long.MIN_VALUE),maxBin=Long.toBinaryString(Long.MAX_VALUE);
System.out.println("Number of bits in Min Long : "+minBin.length()+", Max Long : "+maxBin.length());
Output:
Number of bits in Min Long : 64, Max Long : 63 //1 extra bit in min long to represent sign
According to Java documentation, a long type variable always is 64 bits long. If you mean to count how many bits there are between the least significant bit to the first most significant bit set to 1 then you can compute:
int usedBits( long time )
{
if( time != 0 )
return (int)( Math.log( time ) / Math.log( 2 ) ) + 1;
else
return 0;
}
The number of bits used are always 64. The number of bits set can be 0 and 64 (You should assume it can be anything else). The top bit set can be determined, but is highly unlikely to be useful. In short, you don't need to know.
If you want to print a fairly random number with a fixed width of digits or in hex, this is a printing/formatting issue and you can determine this with printf.
精彩评论