/*
* Enhydra Java Application Server Project
*
* The contents of this file are subject to the Enhydra Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License on
* the Enhydra web site ( http://www.enhydra.org/ ).
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific terms governing rights and limitations
* under the License.
*
* The Initial Developer of the Enhydra Application Server is Lutris
* Technologies, Inc. The Enhydra Application Server and portions created
* by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
* All Rights Reserved.
*
* Contributor(s):
*
* $Id: HexEncoder.java,v 1.15 2005/06/13 09:26:06 draganr Exp $
*/
package com.lutris.util;
import java.io.*;
import java.text.*;
/**
* Various conversion methods.
* These methods are mostly used to convert internal java data
* fields into byte arrays or strings for use in 8 bit ASCII fields.
*
* @author Mike Ward
*/
public class HexEncoder {
/**
* Hexadecimal characters corresponding to each half byte value.
*/
private static final char[] HexChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Converts a long integer to an unsigned hexadecimal String. Treats
* the integer as an unsigned 64 bit value and left-pads with the
* pad character of the caller's choice.
*
* @param value The long integer to convert to a hexadecimal string.
* @param len The total padded length of the string. If the number
* is larger than the padded length, then this length
* of the string will be the length of the number.
* @param pad The character to use for padding.
* @return Unsigned hexadecimal numeric string representing
* the specified value.
*/
public static final String toHexString(long value, int len, char pad) {
StringBuffer sb = new StringBuffer(Long.toHexString(value));
int npad = len - sb.length();
while (npad-- > 0) sb.insert(0, pad);
return new String(sb);
}
/**
* Converts an arbitrary array of bytes to ASCII hexadecimal string
* form, with two hex characters corresponding to each byte. The
* length of the resultant string in characters will be twice the
* length of the specified array of bytes.
*
* @param bytes The array of bytes to convert to ASCII hex form.
* @return An ASCII hexadecimal numeric string representing the
* specified array of bytes.
*/
public static final String toHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
int i;
for (i=0; i < bytes.length; i++) {
sb.append(HexChars[(bytes[i] >> 4) & 0xf]);
sb.append(HexChars[bytes[i] & 0xf]);
}
return new String(sb);
}
}