/*
 * BytesToHex.java
 *
 * Copyright 2011 John W Dawson
 *
 * This code is distributed under the terms of the GNU General Public License, version 3
 *
 * Converts a stream of bytes into a hex representation
 */

import java.math.*;
import java.io.*;

public class BytesToHex extends ByteArrayOutputStream
{
  public BytesToHex ()
  {
    super ();
  }
  
  static final String HEX_DIGITS = "0123456789abcdef";
  
  // Return contents of buffer as hex string 
  public String toHexString ()
  {
    // Create a buffer to hold the complete string
    StringBuffer sb = new StringBuffer (count * 2);

    
    // Convert each byte to a 2 digit hex representation and append to buffer
    for (int i = 0; i < count; ++i)
    {
      sb.append (HEX_DIGITS.charAt ((buf[i] >> 4) & 0xF));
      sb.append (HEX_DIGITS.charAt (buf[i] & 0xF));
    }
          
    // Clear the buffer
    this.reset();
    
    return sb.toString();
  }
}
     

