Question about sizeof. I want to reverse bits in number
What will be equivalent of this in Java?
for (i = (sizeof(num)*8-1); i; i--)
开发者_开发技巧
num
is given number, not array. I want to reverse bits in integer.
Java does not have sizeof
. Arrays have the length
property, and many collections have size()
and similar things like that, but a linguistic sizeof
for any arbitrary object is both not supported and not needed.
Related questions
- Is there any sizeof-like method in Java?
- In Java, what is the best way to determine the size of an object?
Getting bits of an integer in LSB-MSB order
To get the bits of an integer from its least significant bit to its most significant bit, you can do something like this:
int num = 0xABCD1234;
System.out.println(Integer.toBinaryString(num));
for (int i = 0; i < Integer.SIZE; i++) {
System.out.print((num >> i) & 1);
}
This prints:
10101011110011010001001000110100 // MSB-LSB order from toBinaryString
00101100010010001011001111010101 // LSB-MSB order from the loop
So in this specific case, the sizeof * 8
translates to Integer.SIZE
, "the number of bits used to represent an int value in two's complement binary form". In Java, this is fixed at 32.
JLS 4.2.1 Integral types and values
For
int
, from-2147483648
to2147483647
, inclusive
This loop is likely iterating over an array in reverse order. In this case, it is an array of 'num' objects, and there are 8 elements in the array (the '-1' is necessary because an array of 8 elements has valid indices 0...7).
To do that in Java, the equivalent would be:
for(int i = array.length-1; i >= 0; --i)
in C/C++, the sizeof operator tells you how many bytes a variable or type takes on the current target platform. That is to say, it depends on the target platform, and therefore there is a keyword for discovering it.
Java targets a virtual machine, and the size of types is constant.
If num is an int, it is 4 bytes (32-bits). If it is long, it is 8 bytes (64 bits).
Furthermore, you cannot treat a variable as an array of bytes. You have to use bitwise operators (shifts, and, or etc) to manipulate the bits in a primitive like an int or long.
There isn't a direct equivalent. The sizeof returns the size of a type or the type of the expression in bytes, and this information is not available in Java.
It's not required as the sizes in bytes of the built-in types are fixed, lengths of arrays are obtained using the .length
psuedo-field, and memory for objects is allocated using new
, so the object size is not required.
If you tell use what the type of num is, then it can be translated.
In addition to polygenelubricants' answer, there's another way to reverse the bits of an integer in Java:
int reversed = Integer.reverse(input);
Easy!
It's worth checkout the source code for Integer.reverse, it's rather nifty (and extremely scary).
精彩评论