0

Hey,

I have the following code in C-Sharp:
byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);

What's the equivalent in Java ?

Thanks !

2
Contributors
3
Replies
5
Views
4 Years
Discussion Span
Last Post by liran
0

I think what you want is

byte newByte = Byte.parseByte(hex,16);

Be aware that I have not tested this. I know what it does in Java, but I haven't tried your C# code, and the meaning of System.Globalization.NumberStyles.HexNumber seems a bit odd. Apparently it "Indicates that the AllowLeadingWhite, AllowTrailingWhite, and AllowHexSpecifier styles are used," and AllowHexSpecifier doesn't do what it sounds like it does. Instead of allowing "0x" it actually forbids it. And I'm not sure that my Java version behaves the same way as C# with things like negative numbers.

At least I'm pretty sure it does what Byte.parseByte(hex,16) does in most cases that matter.

1

You should also be aware that Byte.parseByte(hex,16) will throw a NumberFormatException if hex is above 7F or below -80, because that is the range of legal values for a signed byte. You can use (byte)Integer.parseInt(hex,16) if you want to parse bytes upto FF, but then you may want to add your own checks that hex is within range since Integer.parseInt will parse values far above FF without complaint.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.