I need to switch the first half and the second half of a byte: Make 0011 0101 to 0101 0011
for example
I thought it might work this way:
For example, i have 1001 1100
i bitshift
to the left 4
times and get 1111 1001
(because if the first bit is a 1 the others become a one too)
i bitshift to the right 4
times and get 1100 0000
(the second half of the byte gets filled with 0s)
i don't want 1111 1001
but 0000 1001
so i do 0x00001111 & 1111 1001
(which filters the frist 4 bits) to make 1111 1001 to 0000 1001
then i add everything up:
0000 1001 + 1100 0000 = 1100 1001
I got this:
bytes[i] = (byte) (( 0x00001111 & (bytes[i] >> 4)) + (bytes[i] << 4) );
here is one output: 11111111 to 00000001
I do not really understand why this is happening, I know the binary System and I think I know how bitshifting works but I can't explain this one. Sorry for bad english :)