Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

c# - Converting little endian to int

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...