c# 十六进制与十进制 转换
十进制转成十六进制
1.方式一:手动位移 public static byte[] intToBytes(int value) { byte[] src = new byte[4]; src[3] = (byte)((value >> 24) & 0xFF); src[2] = (byte)((value >> 16) & 0xFF); src[1] = (byte)((value >> 8) & 0xFF); src[0] = (byte)(value & 0xFF); return src; } public static int bytesToInt(byte[] src, int offset) { int value; value = (int)((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 2] & 0xFF) << 16) | ((src[offset + 3] & 0xFF) << 24)); return value; } 2.方式二:使用BitConverter public static int IntToBitConverter(int num) { int temp = 0; byte[] bytes = BitConverter.GetBytes(num);//将int32转换为字节数组 temp = BitConverter.ToInt32(bytes, 0);//将字节数组内容再转成int32类型 return temp; }
十六进制与十进制,整数互转
//十六进制byte数组转为 int 十进制 byte[] d1 = new byte[4] {0x34,0xFB,0x5E,0x38 }; if (BitConverter.IsLittleEndian) Array.Reverse(d1); //need the bytes in the reverse order int value = BitConverter.ToInt32(d1, 0); ///十六进制数字字符串转为int 十进制 int va = Convert.ToInt32("34FB5E38", 16);
十六进制与字符串互转:
public static byte[] StringToBytes(string TheString) { Encoding FromEcoding = Encoding.GetEncoding("UTF-8"); Encoding ToEcoding = Encoding.GetEncoding("GB2312"); byte[] FromBytes = FromEcoding.GetBytes(TheString); byte[] ToBytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes); return ToBytes; } public static string BytesToString(byte[] Bytes) { string Mystring; Encoding FromEcoding = Encoding.GetEncoding("GB2312"); Encoding ToEcoding = Encoding.GetEncoding("UTF-8"); byte[] ToBytes = Encoding.Convert(FromEcoding, ToEcoding, Bytes); Mystring = ToEcoding.GetString(ToBytes); return Mystring; }