c# - 如何使用bitConverter.ToInt32方法从c#中的大端获取小端数据? [英] How to get little endian data from big endian in c# using bitConverter.ToInt32 method?

查看:122
本文介绍了c# - 如何使用bitConverter.ToInt32方法从c#中的大端获取小端数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 制作应用程序,它有一个包含十六进制值的字节数组.

I am making application in C# which has a byte array containing hex values.

我以 big-endian 的形式获取数据,但我希望以 little-endian 的形式获取数据,并且我正在使用 Bitconverter.toInt32 方法将该值转换为整数.

I am getting data as a big-endian but I want it as a little-endian and I am using Bitconverter.toInt32 method for converting that value to integer.

我的问题是,在转换值之前,我必须将该 4 字节数据从源字节数组复制到临时数组中,然后反转该临时字节数组.

My problem is that before converting the value, I have to copy that 4 byte data into temporary array from source byte array and then reverse that temporary byte array.

我无法反转源数组,因为它还包含其他数据.

I can't reverse source array because it also contains other data.

因此我的应用程序变得很慢.

Because of that my application becomes slow.

在代码中,我有一个源字节数组 waveData[],其中包含大量数据.

In the code I have one source array of byte as waveData[] which contains a lot 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?

推荐答案

如果你知道数据是 big-endian,也许只需手动进行:

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.

另一种方法是对数组进行洗牌:

Another approach would be to shuffle the array:

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;

我发现第一个更具可读性,并且没有分支/复杂的代码,所以它也应该运行得非常快.第二个也可能在某些平台上遇到问题(CPU 已经在运行 big-endian).

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).

这篇关于c# - 如何使用bitConverter.ToInt32方法从c#中的大端获取小端数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆