I have an int value which needs to be converted into a byte array. How do you go about doing this in Objective-C? Are there methods to do this?
Thank you,
I have an int value which needs to be converted into a byte array. How do you go about doing this in Objective-C? Are there methods to do this?
Thank you,
Converted in what way? Do you want it in little endian, big endian, or native byte order? If you want it in native byte order, then all you need to do is:
int val = //... initialize integer somehow char* bytes = (char*) &val; int len = sizeof(int);
That said, the best way to manipulate the bytes of an integer is to do bitwise operations. For example, to get the lowest order byte, you can use val&0xFF, to get the next 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 those kinds of things, you really should include <
inttypes.h
>
;, and use uint8_t
, uint16_t
, uint32_t
, or uint64_t
, depending on how large an integer you want; otherwise, you cannot reliably play around with larger numbers of bytes.
I suspect that what you want to do is to pass this byte array somewhere possibly to a NSMutableData object. You just pass the address &val
Example:
[myData appendBytes:&myInteger length:sizeof(myInteger)];
This link is more complete and deals with endianness: