java - Return the result of swapping the two lower-order bytes of X -
problem , solution:
/** return result of swapping 2 lower-order bytes of x. * example, if x 0x12345678, swap(x) 0x12347856. */ static int swaplower(int x) { /* solution */ int lower = x & 0x0000ffff; int upper = x & 0xffff0000; return upper | (0xffff & ((lower << 8) | (lower >> 8))); }
i confused how understand solution. tried working through logic did not understand.
also, don't know how come solution in first place!
edit:
properties:
x & 1 = x x & 0 = 0 x | 1 = 1 x | 0 = x
int lower = x & 0x0000ffff = x & 0b00000000000000001111111111111111 = 0b0000000000000000x15 ... x0
int upper = x & 0xffff0000 = x & 0b11111111111111110000000000000000 = 0bx31 ... x160000000000000000
lower << 8 = 0b0000000000000000x15 ... x0 << 8 = 0b00000000x15 ... x000000000
lower >> 8 = 0b0000000000000000x15 ... x0 >> 8 = 0bssssssss00000000x15 ... x8
- (assuming
x
signed number,s
sign bit; it's 0 ifx
positive , 1 ifx
negative)
- (assuming
(lower << 8) | (lower >> 8) = 0b00000000x15 ... x000000000 | 0bssssssss00000000x15 ... x8 = 0bssssssssx15 ... x0x15 ... x8
0xffff & ((lower << 8) | (lower >> 8)) = 0b000000000000000001111111111111111 & 0bssssssssx15 ... x0x15 ... x8 = 0b00000000000000000x7 ... x0x15 ... x8
upper | (0xffff & ((lower << 8) | (lower >> 8))) = 0bx31 ... x160000000000000000 | 0b00000000000000000x7 ... x0x15 ... x8 = x31 ... x16x7 ... x0x15 ... x8
yes, that's harder understand necessary.
i think easier understand:
int lowest2 = (x & 0x000000ff) << 8; // lowest byte moved 8 bits left int nextlowest2 = (x & 0x0000ff00) >> 8; // next lowest byte move 8 bits right int upper4 = (x & 0xffff0000); return upper4 | lowest2 | nextlowest2;
then when x = 0x12345678:
upper4 | lowest2 | nextlowest2 = 0x12340000 | 0x00007800 | 0x00000056;
but of course if analyse solution gave same thing:
if upper , lower defined as:
int lower = x & 0x0000ffff int upper = x & 0xffff0000;
then:
x = 0x12345678 lower = 0x00005678 (lower << 8) = 0x00567800 (lower >> 8) = 0x00000056 ((lower << 8) | (lower >> 8)) = 0x00567856 (0xffff & ((lower << 8) | (lower >> 8))) = 0x00007856 upper = 0x12340000 upper | (0xffff & ((lower << 8) | (lower >> 8))) = 0x12345678
Comments
Post a Comment