转换小尾数为int [英] Converting little endian to int

查看:117
本文介绍了转换小尾数为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我认为这个问题是不是C#独立。但也可以如C等语言使用。






我现在正试图解析存储整数4个字节的小尾数格式的文件格式。
TBH,我不知道我怎么了小端格式也不是big-endian格式的作品。



但需要将它们转换成可用的int变量



例如,
02 00 00 00 = 2



到目前为止,我有这代码转换的前2个字节(我用FileStream.Read将原始DATAS存储到缓冲区变量)

  INT NUM =((缓冲[5]所述;&下; 8)+缓冲区[4]); 



但它只会转换前两个字节。 (在本例02 00,而不是02 00 00 00)



任何形式的帮助,将不胜感激:)


解决方案

  INT GetBigEndianIntegerFromByteArray(字节[]的数据,诠释了startIndex){
回报率(数据[的startIndex<< 24)$ b $ C | (数据[了startIndex + 1];&下; 16)
| (数据[了startIndex + 2]所述;&下; 8)
|数据[了startIndex + 3];
}

INT GetLittleEndianIntegerFromByteArray(字节[]的数据,诠释了startIndex){
回报率(数据[的startIndex + 3] LT;< 24)
| (数据[了startIndex + 2]所述;&下; 16)
| (数据[了startIndex + 1];&下; 8)
|数据[的startIndex]
}


First of all, I think this question is not C# independent. But can also be used in other languages like C.


I'm now trying to parse a file format which stores integers in 4 bytes little-endian format. TBH, I don't know how the little-endian format nor big-endian format works.

But I need to convert them into an usable int variable.

For example, 02 00 00 00 = 2

So far, I have this code to convert the first 2 bytes: (I used FileStream.Read to store the raw datas into a buffer variable)

        int num = ((buffer[5] << 8) + buffer[4]);

But it will only convert the first two bytes. (02 00 in the example, not 02 00 00 00)

Any kind of help would be appreciated :)

解决方案

int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) {
    return (data[startIndex] << 24)
         | (data[startIndex + 1] << 16)
         | (data[startIndex + 2] << 8)
         | data[startIndex + 3];
}

int GetLittleEndianIntegerFromByteArray(byte[] data, int startIndex) {
    return (data[startIndex + 3] << 24)
         | (data[startIndex + 2] << 16)
         | (data[startIndex + 1] << 8)
         | data[startIndex];
}

这篇关于转换小尾数为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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