C# byte[] 、int 和 string 互转

该文介绍了C#中几种数据类型与byte数组之间的转换方法,包括int转byte[](高位在前,低位在后),字符串转ASCIIbyte[],十六进制字符串转byte[],以及从byte[]获取子数组,将byte转为十六进制字符串,byte[]转为int字符串等操作。
摘要由CSDN通过智能技术生成

1、int整形转为byte[]数组:高位存储在前,低位存储在后    

public static byte[] IntToByte(this int source, int fromebase = 4)
{
	List<byte> buff = new List<byte>();
	for (int i = fromebase - 1; i >= 0; i--)
	{
		buff.Add((byte)(source>>(8 * i)));
	}
	return buff.ToArray();
}

2、字符串转对应ASCII码,byte[]数组    

    public static byte[] StringToByte(this string source)
    {
        return Encoding.Default.GetBytes(source);
    }

3、十六进制字符串数组转为byte[]数组   

    public static byte[] HexStringToByte(this string source)
    {
        if (string.IsNullOrEmpty(source))
            return new byte[0];
        List<byte> buff = new List<byte>();
        for (int i = 0; i < source.Length; i += 2)
        {
            buff.Add(Convert.ToByte(source.Substring(i, 2), 16));
        }
        return buff.ToArray();
    }

4、获取byte[]指定的区域的数组,offset:首地址;count:个数

    public static byte[] GetBytes(this byte[] source, int offset, int count)
    {
        byte[] buff = new byte[count];
        int total = offset + count;
        int index = 0;
        for (int i = offset; i < total; i++)
        {
            buff[index] = source[i];
            index++;
        }
        return buff;
    }

5、byte转为十六进制字符串 并补位  

    public static string ToHexString(this byte b)
    {
        return b.ToString("X2");
    }

6、指定byte[]区域内 转十六进制字符串

    public static string ToHexString(this byte[] datas, int offset, int count)
    {
        StringBuilder str = new StringBuilder();
        int total = offset + count;
        for (int i = offset; i < total; i++)
        {
            str.Append(datas[i].ToString("X2"));
        }
        return str.ToString();
    }

7、byte转int字符串

    public static string ToIntString(this byte b)
    {
        return b.ToString("D");
    }

8、byte[]转int字符串

    public static string ToIntString(this byte[] datas, int offset, int count)
    {
        StringBuilder str = new StringBuilder();
        int total = offset + count;
        for (int i = offset; i < total; i++)
        {
            str.Append(datas[i].ToString("D"));
        }
        return str.ToString();
    }

9、byte[]转int字符串,split:分割字符串

    public static string ToIntString(this byte[] datas, int offset, int count, string split = "")
    {
        StringBuilder str = new StringBuilder();
        int total = offset + count;
        for (int i = offset; i < total; i++)
        {
            if (i > offset)
            {
                str.Append(split);
            }
            str.Append(datas[i].ToString("D"));
        }
        return str.ToString();
    }

10、整形转byte[]数组:BitConverter.GetBytes,低位在前,高位在后;以字节数组的形式返回指定的 32 位有符号整数值。返回为4的字节数组

int iResult = 20000;
byte[] array = BitConverter.GetBytes(iResult);

11、byte[]数组转整形:BitConverter.ToInt32,低位在前,高位在后

byte[] array = new byte[4]{0x01,0x02,0x03,0x04};
BitConverter.ToInt32(datas,array);

**************************************************************************************************************

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,可以使用多种方法将byte\[\]转换string。其中一种方法是使用System.Text.Encoding类的GetString方法。例如,可以使用UTF8编码将byte\[\]转换string,代码如下: ```csharp string str = System.Text.Encoding.UTF8.GetString(bytes); ``` 另一种方法是使用BitConverter类的ToString方法将byte\[\]转换为十六进制字符串。然后,可以使用Split方法将字符串拆分为字符串数组,并使用Convert.ToByte方法将每个十六进制字符串转换byte。代码如下: ```csharp string str = BitConverter.ToString(bytes); string\[\] tempArr = str.Split('-'); byte\[\] decBytes = new byte\[tempArr.Length\]; for (int i = 0; i < tempArr.Length; i++) { decBytes\[i\] = Convert.ToByte(tempArr\[i\], 16); } ``` 还有一种方法是使用Convert类的ToBase64String方法将byte\[\]转换为Base64字符串,然后使用Convert类的FromBase64String方法将Base64字符串转换byte\[\]。代码如下: ```csharp string str = Convert.ToBase64String(bytes); byte\[\] decBytes = Convert.FromBase64String(str); ``` 最后一种方法是使用HttpServerUtility类的UrlTokenEncode方法将byte\[\]转换为URL安全的字符串,然后使用HttpServerUtility类的UrlTokenDecode方法将URL安全的字符串转换byte\[\]。需要注意的是,这种方法需要依赖System.Web库。代码如下: ```csharp string str = HttpServerUtility.UrlTokenEncode(bytes); byte\[\] decBytes = HttpServerUtility.UrlTokenDecode(str); ``` 请根据你的需求选择适合的方法进行byte\[\]到string转换。 #### 引用[.reference_title] - *1* [C# string类型和byte[]类型相互转换](https://blog.csdn.net/itffscut/article/details/40399135)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C# byte[]数组和string的互相化 (四种方法)](https://blog.csdn.net/pretty_h/article/details/85297935)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值