How to convert int to bytes in Objective-C?

I have an int value that needs to be converted to an array of bytes. How do you do this in Objective-C? Are there any methods for doing this?

Thanks,

+4
source share
2 answers

Converted in what way? Do you want it in a small end, large end or full-scale order? If you want it to be in basically byte order, you only need to:

  int val = // ... initialize integer somehow
 char * bytes = (char *) & val;
 int len ​​= sizeof (int);

However, the best way to manipulate bytes of an integer is to perform bitwise operations. For example, to get the low byte, you can use val & 0xFF to get the next one you use (val>>8)&0xFF , then (val>>16)&0xFF , then (val>>24)&0xFF , etc. .

Of course, it depends on the size of your data type. If you do such things, you should include < inttypes.h > inttypes.h and use uint8_t , uint16_t , uint32_t or uint64_t , depending on how large the integer you want; otherwise, you cannot play reliably with lots of bytes.

+7
source

I suspect you want to pass this byte array somewhere, possibly to an NSMutableData object. You just pass the address & val

Example:

 [myData appendBytes:&myInteger length:sizeof(myInteger)]; 

This link is more complete and deals with content:

Add NSInteger to NSMutableData

+1
source

Source: https://habr.com/ru/post/1307625/


All Articles