开发者

How are the values stored in the C unsigned shorts?

开发者 https://www.devze.com 2023-01-21 08:22 出处:网络
I\'m trying to read a binary file into a C# struct. The file was created from C and the following code creates 2 bytes out of the 50+ byte rows.

I'm trying to read a binary file into a C# struct. The file was created from C and the following code creates 2 bytes out of the 50+ byte rows.

unsigned short nDayTimeBitStuffed = atoi( LPCTSTR( strInput) );
unsigned short nDayOfYear         = (0x01FF & nDayTimeBitStuffed);
unsigned short nTimeOfDay         = (0x01F  &开发者_如何转开发amp; (nDayTimeBitStuffed >> 9) );

Binary values on the file are 00000001 and 00000100.

The expected values are 1 and 2, so I think some bit ordering/swapping is going on but not sure.

Any help would be greatly appreciated.

Thanks!


The answer is 'it depends' - most notably on the machine, and also on how the data is written to the file. Consider:

unsigned short x = 0x0102;
write(fd, &x, sizeof(x));

On some machines (Intel), the low-order byte (0x02) will be written before the high-order byte (0x01); on others (PPC, SPARC), the high-order byte will be written before the low-order one.

So, from a little-endian (Intel) machine, you'd see the bytes:

0x02 0x01

But from a big-endian (PPC) machine, you'd see the bytes:

0x01 0x02

Your bytes appear to be 0x01 and 0x04. Your calculation for 0x02 appears flawed.

The C code you show doesn't write anything. The value in nDayOfYear is the bottom 9 bits of the input value; the nTimeOfDay appears to be the next 5 bits (so 14 of the 16 bits are used).

For example, if the value in strInput is 12141 decimal, 0x2F6D, then the value in nDayOfYear would be 365 (0x16D) and the value in nTimeOfDay would be 23 (0x17).

It is a funny storage order; you can't simply compare the two values whereas if you packed the day of year in the more significant portion of the value and time into the less significant, then you could compare values as simple integers and get the correct comparison.


The expected file contents are very much related to the processor and compiler used to create the file, if it's binary.

I'm assuming a Windows machine here, which uses 2 bytes for a short and puts them in little endian order.

Your comments don't make much sense either. If it's two bytes then it should be using two chars, not shorts. The range of the first is going to be 1-365, so it definitely needs more than a single byte to represent. I'm going to assume you want the first 4 bytes, not the first 2.

This means that the first byte will be bits 0-7 of the DayOfYear, the second byte will be bits 8-15 of the DayOfYear, the third byte will be bits 0-7 of the TimeOfDay, and the fourth byte will be bits 8-15 of the TimeOfDay.

0

精彩评论

暂无评论...
验证码 换一张
取 消