Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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?

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

uint32_t saneValue = insaneValue >> 24;

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

Try using the function NSSwapInt(), i.e.

int x = 0x12345678;
x = NSSwapInt(x);
NSLog (@"%x", x);

Should print “78563412”.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top