在c#中将字节数组转换为整数
问题描述:
float input = 25;
byte[] buffer = BitConverter.GetBytes(input);
缓冲区包含0x00 0x00 0xc8 0x41。我需要将它转换回浮点数,即25.我只知道十六进制值,请告诉我怎么做。
buffer contains 0x00 0x00 0xc8 0x41.I need to convert it back to float i.e 25.I knows only hex values,Please tell how to do it.
答
BitConverter.ToSingle [ ^ ]方法?
eg
What's wrong with BitConverter.ToSingle[^] method?
e.g.
float input = 25;
byte[] buffer = BitConverter.GetBytes(input);
float output = BitConverter.ToSingle(buffer,0);
conversion-binary-value-from-bitarray-to-an-int-and-back-in-c [ ^ ]
how-i-can -convert-bitarray-to-single-int [ ^ ]
检查链接..希望它会有所帮助..
converting-binary-value-from-bitarray-to-an-int-and-back-in-c[^]
how-i-can-convert-bitarray-to-single-int[^]
Check the link..hope it will help..
private Single ConvertHexToSingle(string hexVal)
{
try
{
int i = 0, j = 0;
byte[] bArray = new byte[4];
for (i = 0; i <= hexVal.Length - 1; i += 2)
{
bArray[j] = Byte.Parse(hexVal[i].ToString() + hexVal[i + 1].ToString(), System.Globalization.NumberStyles.HexNumber);
j += 1;
}
Array.Reverse(bArray);
Single s = BitConverter.ToSingle(bArray, 0);
return (s);
}
catch (Exception ex)
{
throw new FormatException("The supplied hex value is either empty or in an incorrect format. Use the " +
"following format: 00000000", ex);
}
}