Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

b = (byte) b >>> 4; /* why isn b 0x0f ?

byte
0
Posted

b = (byte) b >>> 4; /* why isn b 0x0f ?

0

shift right of 0xF1 would successively be (in binary) 0111_1000 then 0011_1100 then 0001_1110 then 0000_1111 */ But that doesn’t happen. The rules of arithmetic in Java say that all operands are converted at least to int before the operation (and possibly to a more capacious type). That means our byte is promoted to an int, so instead of shifting 0xf1, we are shifting 0xfffffff1. If you shift right unsigned 4 places, you get 0x0fffffff. When you cast that to a byte it becomes 0xff, or -1. The bottom line is that the final result is the same as if you’d performed the signed shift because the unsigned shift applied to the intermediate int, not to the original byte. This anomaly means that “>>>” is useless for negative bytes and shorts. It is probably safer and clearer not to use it at all, but to mask and shift like this: // not recommended byte b = -15; b = (byte) (b>>>4); System.out.println(“b= “+Integer.toHexString(b) );// recommended b= -15; b = (byte) ( (b & 0xFF) >> 4 ); System.out

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123