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 !

Recommended Answers

All 3 Replies

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.

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.

Thanks !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.