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
706 views
in Technique[技术] by (71.8m points)

c# - Converting Byte Array To Int24

I am reading a file with BinaryReader.

There are data I want to pull at the address 0x37E but it is int24. So even I read 3 bytes, I can't convert it to int24.

Do you have any suggestion?

I'm using C# and am working on STFS package stuff.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In order to transform a byte array to an int24, you need to know the endianness of the data. This means: the information if 11 22 33 is supposed to mean 0x112233 or 0x332211.

Depending on this endianness, you can convert the data such as

int24 result_bigendian = array[0] * 65536 + array[1] * 256 + array[2] // (1)

or

int24 result_littleendian = array[2] * 65536 + array[1] * 256 + array[0] // (2)

(resp.

int24 result_littleendian = array[0] + array[1] * 256 + array[2] * 65536 // (3)

if you prefer that; note the difference to (1))

I don't know about C#; there may be an easier way to reach the goal.


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

...