c# int与byte[]转换
2014-07-21 21:06
211 查看
网络上总结的方法汇总:
1: public byte[] intToByte(int i) {
byte[] abyte0 = new byte[4];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
return abyte0;
}
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
2: using system;
static void Main(string[] args)
{
byte[] bt=new byte[4];
bt[0] = 255;
bt[1] = 255;
int it=65535 ;
bt = BitConverter.GetBytes(it);
//Console.WriteLine(bt.ToString());
it = BitConverter.ToInt64(bt,0);
//Console.WriteLine(it);
//Console.ReadLine();
}
3:先转换为string再互换?这个没试验成功。
在用第一种方法时很方便;
第二种注意若byte[]维度大于4则会截断;若小于4,会出错,因为内部实现方法就是1:,找不到[3]当然会出错。
当然你可以继续测试,扩展为Int64,相应的byte[]维度需要达到8;同样短了出错,长了截断。
1: public byte[] intToByte(int i) {
byte[] abyte0 = new byte[4];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
return abyte0;
}
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
2: using system;
static void Main(string[] args)
{
byte[] bt=new byte[4];
bt[0] = 255;
bt[1] = 255;
int it=65535 ;
bt = BitConverter.GetBytes(it);
//Console.WriteLine(bt.ToString());
it = BitConverter.ToInt64(bt,0);
//Console.WriteLine(it);
//Console.ReadLine();
}
3:先转换为string再互换?这个没试验成功。
在用第一种方法时很方便;
第二种注意若byte[]维度大于4则会截断;若小于4,会出错,因为内部实现方法就是1:,找不到[3]当然会出错。
当然你可以继续测试,扩展为Int64,相应的byte[]维度需要达到8;同样短了出错,长了截断。
相关文章推荐
- C# int 转换为byte 的浅析
- C# int字节 转换Byte数组 3位
- c# int byte转换
- 【转】c# int 和 byte数组 互相 转换
- 在C# 中将byte[]转换为int和int转换为byte[] 将字符串转byte[]以及反向转
- C#将int数组转换为byte数组
- int/byte/byte[]转换 c#
- 在C# 中将byte转换为int和int转换为byte
- c# int byte转换
- C#中byte[]与string的转换
- C#中有关string和byte[]转换的问题
- c# struct 变量 到 byte[] 变量的转换操作
- C#中string与byte[]的转换帮助类
- C#中string与byte[]的转换帮助类
- C#中string与byte[]的转换帮助类
- 使用BitConverter对int与byte[]类型进行互相转换
- [导入]C#中string与byte[]的转换帮助类
- int整数和byte[]数组互相转换
- [收藏]C#中string与byte[]的转换帮助类-.NET教程,C#语言
- C#中byte[]与string的转换