Byte Signedness And The 0xFF Mask

Bytes store -128..127, so anything above 127 wraps negative; & 0xFF widens to an unsigned int for CRC, hashing, and wire-format work.

JavaData Integrity

Code

snippet
import java.util.HexFormat;

public class ByteSignedness {

    public static void main(String[] args) {
        // 超过 127 的字面量写进 byte 会回绕成负数:byte 的取值范围是 -128..127
        byte raw = (byte) 0xFF;
        System.out.println("raw: " + raw); // -1

        // 参与 I/O(CRC、哈希、网络协议)必须按无符号解释:& 0xFF 抹掉符号扩展
        int unsigned = raw & 0xFF;
        System.out.println("unsigned: " + unsigned); // 255

        // int 强转 byte 只保留低 8 位:高位全部截断
        byte low = (byte) 300;
        System.out.println("low: " + low + " (" + (low & 0xFF) + " unsigned)"); // 44 (44 unsigned)

        // HexFormat 按无符号输出,与内存中的字节一致
        System.out.println("hex: " + HexFormat.of().formatHex(new byte[] {raw, 0x7F})); // ff7f
    }
}

How it works

The code’s whole job belongs to the class ByteSignedness and the function main.

Watch out for

  • Each symbol here is a language built-in, so there is nothing to fetch.

Using it

Signature: public static void main(String[] args)

The run emits 4 labeled sections — raw:, unsigned:, low:, hex: — one per step.

Key statements

int unsigned = raw & 0xFF;
byte raw = (byte) 0xFF;
byte low = (byte) 300;

Interactive Tools for This Topic

FAQ

What does Byte Signedness And The 0xFF Mask print when run?
Invoke the file as-is — the `raw:`, `unsigned:`, `low:` prefixes identify which step printed each line.