如何使用bitConverter.ToInt32方法从大端在c#小尾数数据? [英] How to get little endian data from big endian in c# using bitConverter.ToInt32 method?
问题描述
我想提出在C#中。在该应用程序,我有字节数组包含十六进制值。
i am making application in c#.In that application i have byte array containing hex values.
下面我得到的数据作为大端,但我想它作为一个小尾数。
Here i am getting data as a big endian but i want it as a little endian.
下面我使用 Bitconverter.toInt32
方法转换该值为整数。
Here i am using Bitconverter.toInt32
method for converting that value to integer.
不过,我的问题是转换值之前,我必须复制从源代码的字节数组4字节数据到临时数组,然后扭转这种临时的字节数组。
But my problem is that before converting value,i have to copy that 4 byte data into temporary array from source byte array and then reverse that temporary byte array.
我不能扭转源阵列,因为它包含的其他数据也。
I cant reverse source array because it contains other data also.
由于我的应用程序变得缓慢。
code在这里,我有一个字节一个源阵列waveData [],它包含了很多很多的数据。
Because of that my application becomes slow. code Here i have one source array of byte as waveData[].It contains lot much of data.
byte[] tempForTimestamp=new byte[4];
tempForTimestamp[0] = waveData[290];
tempForTimestamp[1] = waveData[289];
tempForTimestamp[2] = waveData[288];
tempForTimestamp[3] = waveData[287];
int number = BitConverter.ToInt32(tempForTimestamp, 0);
是否有该转换任何其他方法?
Is there any other method for that conversion?
推荐答案
如果您知道数据是大端,也许只是做手工:
If you know the data is big-endian, perhaps just do it manually:
int value = (buffer[i++] << 24) | (buffer[i++] << 16)
| (buffer[i++] << 8) | buffer[i++];
这将可靠地运行任何CPU上了。注 I
是当前偏移到缓冲区中。
this will work reliably on any CPU, too. Note i
is your current offset into the buffer.
另一种方法是洗牌阵列
byte tmp = buffer[i+3];
buffer[i+3] = buffer[i];
buffer[i] = tmp;
tmp = buffer[i+2];
buffer[i+2] = buffer[i+1];
buffer[i+1] = tmp;
int value = BitConverter.ToInt32(buffer, i);
i += 4;
我找到的第一个极大的可读性,并且没有分支机构/复杂的code,所以它应该工作pretty快。第二个也可能会遇到一些平台(其中CPU已经运行大端)的问题。
I find the first immensely more readable, and there are no branches / complex code, so it should work pretty fast too. The second could also run into problems on some platforms (where the CPU is already running big-endian).
这篇关于如何使用bitConverter.ToInt32方法从大端在c#小尾数数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!