Created
July 23, 2012 14:55
-
-
Save toh4649/3164059 to your computer and use it in GitHub Desktop.
byte to string converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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