• Home
  • About

Snippet IT

IT News, Programming, Internet and Blogging

  • Programming and Scripting
  • Tips and Tricks
  • Software and Hardware
  • New and Happening
You are here: Home / Programming and Scripting / Java: Format Bytes Array into Hexadecimal String

Java: Format Bytes Array into Hexadecimal String

May 22, 2009 by Sze Hau Leave a Comment

Sometimes, we may want to format a bytes array into hexadecimal (base-16) format for debugging purpose or for better readability. One byte has 8 bits and one byte can be represent by two hexadecimal characters (0 – 15 and A – F).

You can use the Java’s String.format to print out each byte but I still prefer my own way of doing it, which I believe it will perform a little bit faster. The following code shows the way to convert bytes array into hexadecimal string and vice versa.

 

public class Bytes {

  private final static char[] HEX = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String toHex(byte[] bytes) {
    StringBuilder buffer;

    buffer = new StringBuilder();
    for (byte b : bytes) {
      buffer.append(HEX[(b >> 4) & 0xf]);
      buffer.append(HEX[b & 0xf]);
    }
    return buffer.toString();
  }

  public static byte[] fromHex(String hex) throws NumberFormatException {
    char[] chars;
    char c;
    int i;
    int j;
    byte[] bytes;
    byte b;

    chars = hex.toUpperCase().toCharArray();

    if (chars.length % 2 != 0) {
      throw new NumberFormatException("Incomplete hex value");
    }

    bytes = new byte[chars.length / 2];
    b = 0;
    j = 0;
    for (i = 0; i < chars.length; i++) {
      c = chars[i];
      if (c >= '0' && c <= '9') {
        b = (byte) ((b << 4) | (0xff & (c - '0')));
      } else if (c >= 'A' && c <= 'F') {
        b = (byte) ((b << 4) | (0xff & (c - 'A' + 10)));
      } else {
        throw new NumberFormatException("Invalid hex character: " + c);
      }
      if ((i + 1) % 2 == 0) {
        bytes[j++] = b;
        b = 0;
      }
    }

    return bytes;
  }
}

More from my site

  • Java: Format Integer Into Fixed Width StringJava: Format Integer Into Fixed Width String
  • Java: Format Long Integer Into Hexadecimal StringJava: Format Long Integer Into Hexadecimal String
  • Java: Unlimited Strength Jurisdiction PolicyJava: Unlimited Strength Jurisdiction Policy
  • Java: Static Initializer (Static Constructor)Java: Static Initializer (Static Constructor)
  • Java: How To Select Top N Objects From A ListJava: How To Select Top N Objects From A List
  • Java: How To Implement ungetc in JavaJava: How To Implement ungetc in Java

Filed Under: Programming and Scripting Tagged With: array, byte, format, hexadecimal, Java

About Sze Hau

Geek. Love programming. Coffee addicted. Married with two children. Working towards financial freedom.

Leave a Reply Cancel reply

Advertisement

  • Facebook
  • Google+
  • Instagram
  • Twitter

Email News Letter

Sign up to receive updates daily and to hear what's going on with us

Software and Hardware

MD5 and SHA1 Checksum Using Windows

July 5, 2017 By Sze Hau Leave a Comment

Blog Network

  • Personal Fincance Personal Finance – Personal Money Tips, Stock Investment, Small Business and Make Money Online
  • szehau's weblog Life, Internet, Software, Gadgets, Programming and Investments

Snippet IT

This is the place where I want to share anything about information technology.

Search

Recent

  • MD5 and SHA1 Checksum Using Windows
  • MD5 and SHA1 Checksum Using Linux
  • Java: Unlimited Strength Jurisdiction Policy
  • WordPress: How To Change Admin Username
  • Linux: How To Compress And Decompress Folders And Files

Tags

Adsense advertisement advertising apache blog blogging tips C# EGPC error estimation format format Integer Gmail Google Google Adsense Google Chrome Google Search Engine Google search result how to HTTP internet marketing Java JavaScript Linux money password performance PHP programming search engine optimization secure security short URL SQL static constructor String tiny URL Tips and Tricks twitter video Windows Vista Wordpress wordpress plugin wordpress theme Youtube

Copyright © 2025 · Magazine Pro Theme on Genesis Framework · WordPress · Log in