How do I create class to convert byte to hex string?
I'm a beginner here - this is no doubt easy, but I haven't managed it.
I have lots of places in my program where I need to convert a byte value to a hex string of the form 0xHH.
I can do this as follows:
byte value;
String hex_value = "0x" + String.format("%02x", value);
But this is messy...
Ideally if I've got a byte variable called value, I'd like to be able to include something like value.toHex() in a string expression. How do I do this?
Or is there a better/neater way?
I could extend Byte with a toHex method, but Byte is declared final. How do I get around this?
Thanks - Rowan
Re: How do I create class to convert byte to hex string?
You could use
Code:
String hex_value = String.format("0x%02x", i);
but it's not much better.
The best approach is to create a method in your own class which takes a byte as a parameter and returns the formatted string ie
Code:
private String toHex(byte val) {
return String.format("0x%02x", i);
}