Home > Blockchain >  Get two raw bytes from a single char
Get two raw bytes from a single char

Time:02-06

Size of char in Java is two bytes. How can I get raw bytes 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.

  •  Tags:  
  • java
  • Related