0

I have two code in Java and Nodejs to convert int to byte array:

System.out.println((byte)254);
System.out.println(Integer.toHexString((byte)254));

-2
fffffffe
> parseInt(Buffer.from([254]).toString('hex'), 16)
254
> Buffer.from([254]).toString('hex')
'fe'

compare above 2 codes, I have some questions:

  • why Java prints 254 as -2 in byte but nodejs prints it as 254?
  • Java adds 6 f in the prefix of hex string, but node only prints fe.
  • Are these two byte same in the two lanugages?
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • I don't know nodejs but your code is different in the two isn't it? In the Java, you cast to ```byte``` . Try it without the cast – g00se Aug 19 '22 at 10:43
  • using byte is what I want. I am converting int to byte in the two languages but it gives me different output – Joey Yi Zhao Aug 19 '22 at 10:46
  • ```byte``` is a signed type in Java. The maximum positive value is 127. Depending on what you're doing, you probably don't need to worry – g00se Aug 19 '22 at 10:53
  • Java's byte is an 8-bit signed value. 254 is 0xfe which is -2 in an 8-bit signed, two's complement value. If you widen this (byte to int) then sign extension happens and 0xfe becomes 0xfffffffe. – jarmod Aug 19 '22 at 10:58

0 Answers0