Skip to content

Instantly share code, notes, and snippets.

@toh4649
Created July 23, 2012 14:55
Show Gist options
  • Save toh4649/3164059 to your computer and use it in GitHub Desktop.
Save toh4649/3164059 to your computer and use it in GitHub Desktop.
byte to string converter
class ByteUtil
{
/// <summary>
/// converts bytedata in a byte array to a hexadecimal string
/// </summary>
public static string Byte2String(byte[] b, int offset, int len, string separator)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++)
{
sb.AppendFormat("{0,1:X2}", b[i+offset]);
sb.Append(separator);
}
return sb.ToString();
}
//converts hexadecimal string to a byte array
public static byte[] String2Byte(string nstr)
{
string str = (string)nstr.Clone();
str = str.Replace(" ", "");
str = str.Replace("\t", "");
int lenByte = str.Length / 2;
byte[] ret = new byte[lenByte];
if ((str.Length % 2) != 0) { throw new FormatException(); }
if ( str.Length == 0) { throw new FormatException(); }
for (int i = 0; i < lenByte; i++)
{
string strByte = str.Substring(i * 2, 2);
ret[i] = Convert.ToByte(strByte, 16);
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment