Size of char
in Java is two bytes. How can I get raw byte
s from a char
variable?
var ch = '文';
var b1 = // ?
var b2 = // ?
CodePudding user response:
You can perform bitwise arithmetic on char
to access the individual bytes:
var b1 = (byte) ch;
var b2 = (byte) (ch >> 8);
System.out.printf("x x\n", b1, b2);
// 87 65
CodePudding user response:
This is probably just simple math.
byte b1 = (byte)(0xFF & ch);
byte b2 = (byte)(0xFF & (ch >> 8));
Let us know if this works for you. Be aware that byte
is signed and this will yield negative numbers about half the time.