Reputation:
I'm trying to get the following result 00000000000000101
from this input 5
.
This my code and it doesn't make sense:
public static int get16Bits(int x)
{
System.out.println((x & 0xffff) - ((x & 0x8000) << 1));
return (x & 0xffff) - ((x & 0x8000) << 1);
}
How i can get the 16bits of integer value?
Upvotes: 5
Views: 633
Reputation: 2664
Try changing your return statement a bit:
public static String get16Bits(int x)
{
return (String.format("%016d", Integer.parseInt(Integer.toBinaryString(x))));
}
This should help you.
Upvotes: 8
Reputation:
We can try this code below, we will use for loop :
public void getBits(int number){
String bits = "";
for (int i = 0; i < 16; i++) {
bits = (number & 1) + bits;
number >>= 1;
}
System.out.println("The bits are " + bits);
}
Upvotes: 1
Reputation: 726509
The first part is self-explanatory: the upper 16 bits are removed with & 0xffff
masking.
Subtracting (x & 0x8000) << 1
is a trick that keeps the proper sign of the 16-bit number in the 32-bit result: for example, 0xffff
, a -1 in 16-bit representation, gets converted to 0xffffffff
, which is also -1 in 32-bit representation. This is better than using a conditional, because it is branch-free.
Another trick that you could use is
(((x & 0xFFFF) << 16) >> 16)
This lets the sign bit of 16-bit number "touch" the sign bit of 32-bit number, letting the right shift to sign-extend the result.
Note: If you are looking for a binary String
representation of the number, only x & 0xffff
masking is necessary, because the upper 16 bits are dropped from the string result anyway. This Q&A explains how to obtain a binary representation of an integer with the appropriate number of leading zeros.
Upvotes: 6
Reputation: 2516
Try below :
String.format("%16s", Integer.toBinaryString(5)).replace(' ', '0')
Upvotes: 0