How do I create class to convert byte to hex string?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: How do I create class to convert byte to hex string?

  1. #1
    Join Date
    Nov 2011
    Posts
    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

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,474

    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 code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center