如果是用定义好的 BitConverter.ToSingle 来转换的话,有时候数值会有偏差 ,通过位移的话,就好多了。
因为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};
转载于:https://blog.51cto.com/3836282/886188