I have 64 bit values like this:
1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1101 0011
Decimal value of given stream of number is -45.
I want to split in four 16-bit values:
1111 1111 1111 1111
1111 1111 1111 1111
1111 1111 1111 1111
1111 1111 1101 0011
The input value is signed long.
How to do that in Java?
So far I've tried on this way:
long[] buf = new long[4];
buf[0] = (l&0xFF);
buf[1] = (l&0xFF >> 16) & 0XFF;
buf[2] = (l&0xFF >> 32) & 0XFF;
buf[3] = (l&0xFF >> 48) & 0XFF;
But I think that I mess something with bit shifting logic.
EDIT
The correct solution thanks to @Eugene is:
long l = 45;
long[] buf = new long[4];
buf[0] = (l & 0xFFFF);
buf[1] = l >> 16 & 0XFFFF;
buf[2] = l >> 32 & 0XFFFF;
buf[3] = l >> 48 & 0XFFFF;
long result = ( buf[3] & 0xFFFF) << 48 | ( buf[2] & 0xFFFF) << 32 | (buf[1] & 0xFFFF) << 16 | (buf[0] & 0xFFFF);
System.out.println("Decimal: " + result);
System.out.println("Binary: "Long.toBinaryString(result));
EDIT
you are almost correct (I did way too much typing thinking that you needs the basics also, my bad).
All you have to change is: buf[1] = l >> 16 & 0xFFFF;
I could have written it differently, but that is probably the easiest to understand:
long t = Long.parseUnsignedLong("1111111111111111111111111111111111111111111111111111111111010011", 2);
long twoPower16 = Long.parseLong("1111111111111111", 2);
long one = t & twoPower16;
long two = t >> 16 & twoPower16;
long thr = t >> 32 & twoPower16;
long fou = t >> 48 & twoPower16;
System.out.println(Long.toBinaryString(one));
System.out.println(Long.toBinaryString(two));
System.out.println(Long.toBinaryString(thr));
System.out.println(Long.toBinaryString(fou));
When you do an &
operation(it's called a mask), for example :
0101
0011
----
0001 --> you are keeping the last two bits here
and the >>
is a shift operator. You tell how many bits to shift:
System.out.println(7 >> 1); // 3
That's actually 0111 >> 1
--> 0011
, you have shifted 7
on bit to the left.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.