项目中经常会遇到string、int或者Float类型转换成byte类型,整理了一下!
1、int装换成byte[]
1: byte[] Len = System.BitConverter.GetBytes(ContentLen);
2、byte[]转int
1: /// <summary>
2: /// byte[]转int
3: /// </summary>
4: /// <param name="bytes"></param>
5: /// <returns></returns>
6: public static int ByteToInt(byte[] bytes)
7: {
8: int Len = bytes.Length;
9: int Result = 0;
10: for (int i = 0; i <= Len-1; i++)
11: {
12: int temp = int.Parse(Math.Pow(256,Len-i-1).ToString());
13: Result = Result + ByteToIntNoParse(new byte[] { bytes[i] }) * temp;
14: }
15: return Result;
16: }
3、字节数组转16进制字符串
1: /// <summary>
2: /// 字节数组转16进制字符串
3: /// </summary>
4: /// <param name="bytes"></param>
5: /// <returns></returns>
6: public static string byteToHexStr(byte[] bytes)
7: {
8: string returnStr = "";
9: if (bytes != null)
10: {
11: for (int i = 0; i < bytes.Length; i++)
12: {
13: returnStr += bytes[i].ToString("X2");
14: }
15: }
16: return returnStr;
17: }
4、从16进制转换成汉字
1: /// <summary>
2: /// 从16进制转换成汉字
3: /// </summary>
4: /// <param name="hex"></param>
5: /// <param name="charset">编码,如"utf-8","gb2312"</param>
6: /// <returns></returns>
7: public static string UnHex(string hex, string charset)
8: {
9: if (hex == null)
10: throw new ArgumentNullException("hex");
11: hex = hex.Replace(",", "");
12: hex = hex.Replace("/n", "");
13: hex = hex.Replace("//", "");
14: hex = hex.Replace(" ", "");
15: if (hex.Length % 2 != 0)
16: {
17: hex += "20";//空格
18: }
19: // 需要将 hex 转换成 byte 数组。
20: byte[] bytes = new byte[hex.Length / 2];
21:
22: for (int i = 0; i < bytes.Length; i++)
23: {
24: try
25: {
26: // 每两个字符是一个 byte。
27: bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
28: System.Globalization.NumberStyles.HexNumber);
29: }
30: catch
31: {
32: // Rethrow an exception with custom message.
33: throw new ArgumentException("hex is not a valid hex number!", "hex");
34: }
35: }
36: System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
37: return chs.GetString(bytes);
38: }
5、汉字转换成byte[]
1: byte[] Content = System.Text.Encoding.Default.GetBytes(RegCorssName);