views:

549

answers:

5

I have a bunch of hex values stored as UInt32*

  • 2009-08-25 17:09:25.597 Particle[1211:20b] 68000000
  • 2009-08-25 17:09:25.598 Particle[1211:20b] A9000000
  • 2009-08-25 17:09:25.598 Particle[1211:20b] 99000000

When I convert to int as is, they're insane values when they should be from 0-255, I think. I think I just need to extract the first two digits. How do I do this? I tried dividing by 1000000 but I don't think that works in hex.

+3  A: 

Since you're expecting < 255 for each value and only the highest byte is set in the sample data you posted, it looks like your endianness is mixed up - you loaded a big endian number then interpreted it as little endian, or vice versa, causing the order of bytes to be in the wrong order.

For example, suppose we had the number 104 stored in 32-bits on a big endian machine. In memory, the bytes would be: 00 00 00 68. If you loaded this into memory on a little endian machine, those bytes would be interpreted as 68000000.

Where did you get the numbers from? Do you need to convert them to machine byte order?

Michael
A: 

Dividing by 0x1000000 should work (that is, by 16^6 = 2^24, not 10^6). That's the same as shifting the bits right by 24 (I don't know ObjC syntax, sorry).

wrang-wrang
A: 
dreamlax
+3  A: 

Objective C is essentially C with extra stuff on top. Your usual bit-shift operations (my_int >> 24 or whatever) should work.

ttvd
A: 

This absolutely sounds like an endianness issue. Whether or not it is, simple bit shifting should do the job:

uint32_t saneValue = insaneValue >> 24;
Stephen Canon