如果是用定义好的 BitConverter.ToSingle 来转换的话,有时候数值会有偏差 ,通过位移的话,就好多了。
C# 字节数值Byte[]通过位移与float互转
原创
©著作权归作者所有:来自51CTO博客作者huige2011的原创作品,请联系作者获取转载授权,否则将追究法律责任
因为float占四个byte(字节),所以字节数值用到的也就是前面的四个
1. byte[] bytes = {11,32,3,4};
int no = 0; //转的时候还是要先转成int类型的
no = no | (bytes[0] & 0xff) <<24; //向左偏移
no = no | (bytes[1] & 0xff) <<16;
no = no | (bytes[2] & 0xff) << 8;
no = no | (bytes[3] & 0xff) << 0;
string str = string.Format("{0:N}", no); //保留小数保留2两位
结果:186,647,300.00
然后string 转float就OK了。
2.如果是float转byte[],只要倒过来就行了:
int n = 186647300;
byte [] bytes = new byte[4];
bytes[0] = (byte)(n >> 24);
bytes[1] = (byte)(n >> 16);
bytes[2] = (byte)(n >> 8);
bytes[3] = (byte)(n >> 0);
结果bytes ={11,32,3,4};
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C# 常见的字节数组 byte[] 复制方法
C# 常见的字节数组 byte[] 复制方法byte[] src ={1,2,3,4,5};byte[] dest = new byte[src.p
C# C# byte C#byte数组拷贝 i++ c#