-
November 22nd, 2011, 10:02 AM
#1
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
-
November 22nd, 2011, 01:16 PM
#2
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);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|