// $Id: HexHelper.cs,v 1.1.1.1 2007-07-03 10:15:18 tamirgal Exp $ /// ************************************************************************ /// Copyright (C) 2001, Patrick Charles and Jonas Lehmann * /// Distributed under the Mozilla Public License * /// http://www.mozilla.org/NPL/MPL-1.1.txt * /// ************************************************************************* /// namespace SharpPcap.Packets.Util { /// Functions for formatting and printing binary data in hexadecimal. /// /// /// Patrick Charles and Jonas Lehmann /// /// $Revision: 1.1.1.1 $ /// /// $Author: tamirgal $ /// $Date: 2007-07-03 10:15:18 $ public class HexHelper { /// Convert an int (32 bits in Java) to a decimal quad of the form /// aaa.bbb.ccc.ddd. /// public static System.String toQuadString(int i) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int p = 0; p < 4; p++) { int q = (int) (i & 0xff); sb.Append(q); if (p < 3) sb.Append('.'); i >>= 8; } return sb.ToString(); } /// Convert an int to a hexadecimal string. public static System.String toString(int i) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int p = 0; p < 8; p++) { byte b = (byte) (i & 0xf); sb.Append(nibbleToDigit(b)); i >>= 4; } return sb.ToString(); } /// Converts the lower four bits of a byte into the ascii digit /// which represents its hex value. For example: /// nibbleToDigit(10) produces 'a'. /// public static char nibbleToDigit(byte x) { char c = (char) (x & 0xf); // mask low nibble return (c > 9?(char) (c - 10 + 'a'):(char) (c + '0')); // int to hex char } /// Convert a single byte into a string representing its hex value. /// i.e. -1 -> "ff" /// /// the byte to convert. /// /// a string containing the hex equivalent. /// public static System.String toString(byte b) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(nibbleToDigit((byte) (b >> 4))); sb.Append(nibbleToDigit(b)); return sb.ToString(); } /// Returns a text representation of a byte array. /// /// /// a byte array /// /// a string containing the hex equivalent of the bytes. /// public static System.String toString(byte[] bytes) { System.IO.StringWriter sw = new System.IO.StringWriter(); int length = bytes.Length; if (length > 0) { for (int i = 0; i < length; i++) { sw.Write(toString(bytes[i])); if (i != length - 1) sw.Write(" "); } } return (sw.ToString()); } internal const System.String _rcsid = "$Id: HexHelper.cs,v 1.1.1.1 2007-07-03 10:15:18 tamirgal Exp $"; } }