# Java: Bitshifting bytes

DevFeed: [Java: Bitshifting bytes](<https://devfeed.tech/articles/java-bitshifting-bytes-26039.md>)

Original publisher: [Read original article](<http://doridori.github.io//Java-Bitshifting-Bytes/>)

Author: SystemDotRun

Published: 2015-04-29T00:00:00Z

Content type: tutorial

Language: en

Sources: [SystemDotRun](<https://devfeed.tech/sources/systemdotrun.md>)

Topics: [Java](<https://devfeed.tech/topics/java.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [code](<https://devfeed.tech/tags/code.md>), [java](<https://devfeed.tech/tags/java.md>)

## AI overview

This Java tutorial explains how automatic promotion of byte values to int, combined with signed bytes and bit shifting, can produce unexpected results. It recommends masking with & 0xFF before casting back to byte to preserve the intended low eight bits, especially when emulating unsigned-byte operations or porting code.

## Source excerpt

TL;DR When bitshifting a byte use a & 0xFF mask Working at the bit level in Java can be very frustrating. This is for two reasons There are no unsigned number primitives Automatic type promotion is not intuitive! Looking at type promotion, whenever you use a bitwise operator on a byte variable it is automatically promoted to an int. This means you have to write casting code such as byte b = (byte) (b ^ 8); or b ^= 8 which does the former under-the-hood. This is not too bad really. But the pain starts when working with signed numbers together with int promotion. For example ex1.java For bByte we would expect the result to be 0b1111_1001 as the right Arithmetic shift operator >> fills the left bit depending on the left most (sign) bit (which is 1 when negative ala 2's complement) so the result is as expected. However for cByte we would expect the result to be 0b0000_1001 as the right Logical shift operator >>> should fill the left most bit with 0, but we still get -7! Why is this happening? Well due to the auto int promotion (as a result of using any bitwise operator), when the aByte is promoted to an int, the left most bits of that int are all 1s. In binary form this is 0b1111_1111_1111_1111_1111_1111_1001_0000 before the shift 0b0000_1111_1111_1111_1111_1111_1111_1001 after the shift Due to how casting works when casting down the last 8-bits will be copied directly, hence still giving 0b1111_1001. Not very intuitive when you see aByte >>> 4 imho. So how can we perform >>> operations and get the "intuitive" result of 0b0000_1001? Note: This is useful as to be able to do as Java does not have an unsigned byte type the above kind of operation would let you use a java byte in place of another languages unsigned byte type. This can useful when porting code, for example, if you want to replicate a ubyte >> 4 call then the below will be useful. The answer is to mask the bitwise result before casting back down to byte. We can do this with & 0xFF. This works by persevering o