现在的位置: 首页 > 综合 > 正文

字符与16进制的转换(二)

2018年02月14日 ⁄ 综合 ⁄ 共 4683字 ⁄ 字号 评论关闭

socket发送十六进制字符串 (十六进制字符串与其他类型的转换)

C#  socket发送十六进制字符串 (十六进制字符串与其他类型的转换) 收藏
socket 发送十六进制的字符串

项目用到 socket tcp/ip 发送/接受 十六进制的字符串,因为C# socket 发送接受的都是byte[] (字节数组),现在记录tyte[] 与各数据类型之间的转换

注:

C#的字节数组 byte[] 存放的时间是0-255的整型数据
byte 关键字代表一种整型,该类型按下表所示存储值:

可如下例所示声明并初始化 byte 类型的变量:
byte myByte = 255;
在以上声明中,整数 255 从 int 隐式转换为 byte。如果整数超出了 byte 的范围,将产生编译错误。

引子:

1.字符串转byte[]/byte[]转字符串

2.十六进制字符串转byte[]/byte[]转十六进制字符串

3.十六进制字符串与数值类型之间转换

 4.汉字转十六进制字符串

1.字符串转byte[]/byte[]转字符串

这个是经常用到的,c#中也是比较简单的用

Encoding.UTF8.GetBytes(string data);

Encoding.UTF8.GetString(tyte[] data, 0, length);

要注意的是不同的编码,对数据的长度甚至是内容是有影响的(一般收发两地都使用相同的编码)

2.十六进制字符串转byte[]/byte[]转十六进制字符串

十六进制字符串转byte[]利用Convert.ToByte()方法;byte[]转十六进制字符串利用BitConverter.ToString()或者bytes[i].ToString("X2").

view plaincopy to clipboardprint?
/// <summary>  
/// 16进制字符串转字节数组  
 /// </summary>  
/// <param name="hexString"></param>  
/// <returns></returns>  
private static byte[] strToToHexByte(string hexString)  
{  
    hexString = hexString.Replace(" ", "");  
    if ((hexString.Length % 2) != 0)  
        hexString += " ";  
    byte[] returnBytes = new byte[hexString.Length / 2];  
    for (int i = 0; i < returnBytes.Length; i++)  
        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);  
    return returnBytes;  
}  
 
/// <summary>  
/// 字节数组转16进制字符串  
 /// </summary>  
/// <param name="bytes"></param>  
/// <returns></returns>  
public static string byteToHexStr(byte[] bytes)  
{  
    string returnStr = "";  
    if (bytes != null)  
    {  
        for (int i = 0; i < bytes.Length; i++)  
        {  
            returnStr += bytes[i].ToString("X2");  
        }  
    }  
    return returnStr;  

        /// <summary>
        /// 16进制字符串转字节数组
         /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
            return returnBytes;
        }

        /// <summary>
        /// 字节数组转16进制字符串
         /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

另外,更简单的

byte[] 转十六进制字符串还可以利用BitConverter.ToString方法,这个更容易使用。

string str0x = BitConverter.ToString(byte[] tyt,0,length);

返回的字符串是带“-”分离的十六进制字符串,可以去掉:

string str0x = BitConverter.ToString(byte[] tyt,0,recv).Replace("-", "");

BitConverter类提供基础数据类型与字节数组相互转换的方法。

3.十六进制字符串与数值类型之间转换

十六进制字符串与数值类型之间转换主要用到的类有 BitConverter 、Int32、 String、 Convert

Int32.Parse(),uint.Parse(),

BitConverter.GetBytes(),BitConverter.ToSingle(),

String.Format()

Convert.ToInt32(),Convert.ToByte()等方法

具体参考上篇blog

4.汉字转十六进制字符串

view plaincopy to clipboardprint?
/// <summary>  
/// 从汉字转换到16进制  
 // </summary>  
/// <param name="s"></param>  
/// <param name="charset">编码,如"utf-8","gb2312"</param>  
/// <param name="fenge">是否每字符用逗号分隔</param>  
/// <returns></returns>  
public static string ToHex(string s, string charset, bool fenge)  
{  
    if ((s.Length % 2) != 0)  
    {  
        s += " ";//空格  
        //throw new ArgumentException("s is not valid chinese string!");  
    }  
    System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);  
    byte[] bytes = chs.GetBytes(s);  
    string str = "";  
    for (int i = 0; i < bytes.Length; i++)  
    {  
        str += string.Format("{0:X}", bytes[i]);  
        if (fenge && (i != bytes.Length - 1))  
        {  
            str += string.Format("{0}", ",");  
        }  
    }  
    return str.ToLower();  
}  
 
/// <summary>  
/// 从16进制转换成汉字  
/// </summary>  
/// <param name="hex"></param>  
/// <param name="charset">编码,如"utf-8","gb2312"</param>  
/// <returns></returns>  
public static string UnHex(string hex, string charset)  
{  
    if (hex == null)  
        throw new ArgumentNullException("hex");  
    hex = hex.Replace(",", "");  
    hex = hex.Replace("/n", "");  
    hex = hex.Replace("//", "");  
    hex = hex.Replace(" ", "");  
    if (hex.Length % 2 != 0)  
    {  
        hex += "20";//空格  
    }  
    // 需要将 hex 转换成 byte 数组。  
    byte[] bytes = new byte[hex.Length / 2];  
 
    for (int i = 0; i < bytes.Length; i++)  
    {  
        try 
        {  
            // 每两个字符是一个 byte。  
            bytes[i] = byte.Parse(hex.Substring(i * 2, 2),  
            System.Globalization.NumberStyles.HexNumber);  
        }  
        catch 
        {  
            // Rethrow an exception with custom message.  
            throw new ArgumentException("hex is not a valid hex number!", "hex");  
        }  
    }  
    System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);  
    return chs.GetString(bytes);  

抱歉!评论已关闭.