Skip to content

Instantly share code, notes, and snippets.

@akirad
Created April 23, 2016 10:44
Show Gist options
  • Save akirad/bb401fd678788e2cfa31122373dabee8 to your computer and use it in GitHub Desktop.
Save akirad/bb401fd678788e2cfa31122373dabee8 to your computer and use it in GitHub Desktop.
A memo to use byte in java code.
public class testByte {
public static void main(String[] args) {
byte byteData = (byte) 0xC7; // 11000111
// If there is no "(byte)", 0xC7 is looked as int.
System.out.println(byteData); // -57
int intData = 0xC7; // 00000000 00000000 00000000 11000111
System.out.println(intData); // 199
int castedData = (int)byteData; // 11111111 11111111 11111111 11000111
System.out.println(castedData); // -57
int positiveNumber = byteData & 0xff; // 11111111 11111111 11111111 11000111 & 00000000 00000000 00000000 11111111
// 0xff is looked as int, so this is "int" & "int".
// Result: 00000000 00000000 00000000 11000111
System.out.println(positiveNumber); // 199
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment