The <code>byte</code> Primitive in Java β 8-bit Signed Integer
byte is an 8-bit signed two's-complement integer ranging from -128 to 127. You almost never declare a single byte β you use byte[] for binary data: files, network packets, hashes, image buffers.
Why signed bytes hurt
byte b = (byte) 200; // cast needed β 200 overflows byte
System.out.println(b); // -56, because 200 wraps to -56
int unsigned = b & 0xFF; // 200 β classic trick to read as unsigned
int unsigned2 = Byte.toUnsignedInt(b); // 200 β Java 8+, clearer
byte[] for binary data
byte[] bytes = Files.readAllBytes(path);
byte[] hash = MessageDigest.getInstance("SHA-256").digest(input);
byte[] enc = Base64.getDecoder().decode("SGVsbG8="); // "Hello"
// Convert between byte[] and String β ALWAYS specify a charset
String s = new String(bytes, StandardCharsets.UTF_8);
byte[] b = "hello".getBytes(StandardCharsets.UTF_8);
Hex formatting
// Java 17+
HexFormat.of().formatHex(hash); // "a591a6d40bf420..."
// Older
StringBuilder sb = new StringBuilder();
for (byte b : hash) sb.append(String.format("%02x", b));
Common mistakes
- Reading a byte as unsigned by accident β
byte b = (byte) 0xFF; int i = b;gives-1, not255. Useb & 0xFF. - Missing charset on
getBytes()/new String(bytes)β uses the platform default, which varies. Always pass a charset. - Using
bytefor small positive counters β no memory win versusint, and you lose the top half of the range. Just useint.
Related
Pillar: Java primitives. Tool: Base64 Encoder/Decoder. See also char.