• 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 Long Integer Into Hexadecimal String

Java: Format Long Integer Into Hexadecimal String

August 18, 2009 by Sze Hau 2 Comments

In software programming, sometime you may want to convert a long integer or integer into hexadecimal string for viewing purpose or also as a text format to be stored in text file or database.

The Java API itself does not have a class or function to convert a long into a fixed 16 characters hexadecimal string or an integer into  fixed 8 characters hexadecimal string.

The Java’s Long.toHexString(long i) or Integer.toHexString(int i) only able to convert the integer value to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s and it does not support the reverse way (from hexadecimal string to long integer value).

I wrote a simple class to convert a long integer value into fixed length hexadecimal string and vice versa.

public class Hex {

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

  public static long toLong(String hexadecimal) throws NumberFormatException{
    char[] chars;
    char c;
    long value;
    int i;
    byte b;

    if (hexadecimal == null)
      throw new IllegalArgumentException();

    chars = hexadecimal.toUpperCase().toCharArray();
    if (chars.length != 16)
      throw new HexValueException("Incomplete hex value");

    value = 0;
    b = 0;
    for (i = 0; i < 16; i++) {
      c = chars[i];
      if (c >= '0' && c <= '9') {
        value = ((value << 4) | (0xff & (c - '0')));
      } else if (c >= 'A' && c <= 'F') {
        value = ((value << 4) | (0xff & (c - 'A' + 10)));
      } else {
        throw new NumberFormatException("Invalid hex character: " + c);
      }
    }

    return value;
  }

  public static String fromLong(long value) {
    char[] hexs;
    int i;
    int c;

    hexs = new char[16];
    for (i = 0; i < 16; i++) {
      c = (int)(value & 0xf);
      hexs[16-i-1] = HEX[c];
      value = value >> 4;
    }
    return new String(hexs);
  }

  public static void main(String[] arg) {
    int i;
    long[] test = { -1234567890, 1234567890, 987654321, -987654321, 0xFFFFFFFFFFFFFFFFl, 0x1234567890FFFFFFl };
    long v;
    String s;

    for (i = 0; i < test.length; i++) {
      s = Hex.fromLong(test[i]);
      v = 0;
      try {
        v = Hex.toLong(s);
      } catch(NumberFormatException ex) {
        System.err.println(ex.getMessage());
      }
      if (v != test[i]) {
        System.err.println("Not same " + test[i] + " " + v);
        System.exit(1);
      }
    }
    System.err.println("Test completed satisfactory");
  }
}

To convert long integer into 16 characters hexadecimal string:

String result = Hex.fromLong(1234567890);

To convert  16 characters hexadecimal string into long integer:

long result = Hex.toLong("00000000499602D2");

The Hex class above can be easily modified to support integer and short value by changing the data type and its size (e.g. integer has 4 bytes or 8 characters of hexadecimal and short has 2 bytes or 4 characters of hexadecimal).

More from my site

  • Java: Format integer into number of decimal places and performanceJava: Format integer into number of decimal places and performance
  • Java: Format Integer Into Fixed Width StringJava: Format Integer Into Fixed Width String
  • Java: How To Select Top N Objects From A ListJava: How To Select Top N Objects From A List
  • Java: How To Create A Simple Web Server Using HttpServerJava: How To Create A Simple Web Server Using HttpServer
  • Java: Continuously Read Data From FileChannel Without MappedByteBufferJava: Continuously Read Data From FileChannel Without MappedByteBuffer
  • Java: Loading Large Data into JTable or JListJava: Loading Large Data into JTable or JList

Filed Under: Programming and Scripting Tagged With: DecimalFormat, Float, format, format Integer, how to, Java, Long, String

About Sze Hau

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

Comments

  1. Olivier says

    May 10, 2010 at 9:52 pm

    You could also use

    Long.toString(, 16)

  2. szehau says

    May 10, 2010 at 9:58 pm

    Hi, Long.toString() does not return a fixed size string. 🙂

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