Question

I am making an app that downloads a 32bit integer from server, and use the first 16bit and second 16bit for different purposes...

I am responsible for the second 16bit, which should be used to form an int, I know I should use bitwise operation to do this, but unable to achieve, below is the code that I am using, please give me more information.

        //CID is a 32bit integer, in nslog it shows as 68913219 - its different for every user
        Byte lowByte = (CID>>16)&0xFF; //the 3rd byte
        Byte highByte = (CID>>24)&0xFF; //the 4th byte
        uint16_t value = lowByte & highByte; //combine, but the result is 0.
Was it helpful?

Solution

uint16_t value = lowByte & highByte; //combine, but the result is 0.

This is not how you combine two bytes into a single uint16_t: you are ANDing them in place, while you need to shift the high byte, and OR it with the low byte:

uint16_t value = lowByte | (((uint16_t)highByte) << 8);

However, this is suboptimal in terms of readability: if you start with a 32-bit integer, and you need to cut out the upper 16 bits, you could simply shift by 16, and mask with 0xFFFF - i.e. the same way that you cut out the third byte, but with a 16-bit mask.

OTHER TIPS

You shouldn't need to do this byte-by-byte. Try this:

   //CID is a 32bit integer, in nslog it shows as 68913219 - its different for every user
    uint16_t value = (CID>>16)&0xffff;

You can also use NSData.

If you have this integer:

int i = 1;

You can use :

NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];

and then, to get the second 16bit do:

int16_t recover; [data getBytes: &recover range: NSMakeRange(2, 2)]

Then you have your 16 bits on "recover".

Maybe this way is not so efficient like bit operation, but it is clearer.

:D

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