4

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,

nall
  • 15,899
  • 4
  • 61
  • 65
suse
  • 10,503
  • 23
  • 79
  • 113
  • Possible duplicate: [Stackoverflow - Store an int in a char array?](http://stackoverflow.com/questions/1522994/store-an-int-in-a-char-array). At the very least it can get you to `char[]`. –  Apr 22 '10 at 06:21

2 Answers2

6

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.

Joel Fischer
  • 6,521
  • 5
  • 35
  • 46
Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • Assuming you know that it's an integer, couldn't you just use a loop and use multiples of 8 to reliably play around with their bytes using the length you determine from `sizeof()`? – Joel Fischer Mar 10 '14 at 15:04
1

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:

Append NSInteger to NSMutableData

Community
  • 1
  • 1
  • 1
    For an int type data i.e. 21 it will return 15 00 00 00 in the array of byte or as NSData, or in byte array. {15, 00, 00, 00}. But sometimes I want it in reverse order as, <00 00 00 15> in hex or in array as int (21) = {00, 00, 00, 15}. In that case this approach will not work. – karim Dec 12 '12 at 21:23
  • @karim Have you found a solution yet? – Kaaaaai Dec 25 '22 at 04:15
  • @Kaaaaai No, at least at that time. I am not working with objc for long time now. – karim Dec 26 '22 at 16:49