您的位置:首页 > 编程语言 > C#

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;同样短了出错,长了截断。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: