Mega Code Archive
Hex Encoding
using System;
using System.Text;
namespace MOM.Utility
{
///
/// Summary description for HexEncoding.
///
public class HexEncoding
{
public HexEncoding()
{
//
// TODO: Add constructor logic here
//
}
public static int GetByteCount(string hexString)
{
int numHexChars = 0;
char c;
// remove all none A-F, 0-9, characters
for (int i=0; i
/// Creates a byte array from the hexadecimal string. Each two characters are combined
/// to create one byte. First two hexadecimal characters become first byte in returned array.
/// Non-hexadecimal characters are ignored.
///
/// string to convert to byte array
/// number of characters in string ignored
/// byte array, in the same left-to-right order as the hexString
public static byte[] GetBytes(string hexString, out int discarded)
{
discarded = 0;
string newString = "";
char c;
// remove all none A-F, 0-9, characters
for (int i=0; i
/// Determines if given string is in proper hexadecimal string format
///
///
///
public static bool InHexFormat(string hexString)
{
bool hexFormat = true;
foreach (char digit in hexString)
{
if (!IsHexDigit(digit))
{
hexFormat = false;
break;
}
}
return hexFormat;
}
///
/// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9)
///
/// Character to test
/// true if hex digit, false if not
public static bool IsHexDigit(Char c)
{
int numChar;
int numA = Convert.ToInt32('A');
int num1 = Convert.ToInt32('0');
c = Char.ToUpper(c);
numChar = Convert.ToInt32(c);
if (numChar >= numA && numChar < (numA + 6))
return true;
if (numChar >= num1 && numChar < (num1 + 10))
return true;
return false;
}
///
/// Converts 1 or 2 character string into equivalant byte value
///
/// 1 or 2 character string
/// byte
private static byte HexToByte(string hex)
{
if (hex.Length > 2 || hex.Length <= 0)
throw new ArgumentException("hex must be 1 or 2 characters in length");
byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return newByte;
}
}
}