tags:

views:

178

answers:

1

How do i convert integer to bytes string (NSString of bytes) ,

I used the below code char barr[4];
barr[0] = (unsigned int) (num & 0xff);
barr[1] = (unsigned int) ((num >>8) & 0xff);
barr[2] = (unsigned int) ((num>>16) & 0xff);
barr[3] = (unsigned int) (num >>24);

NSString *str = [NSString stringwithformat:@"%x",barr];

but i am getting "BFFFF648" but not in binary data which i want such that NSlog will print unreadable binary data?

+1  A: 

If you actually want a byte string: NSString is not the right data structure to represent bytes. It's meant to represent text, and is subject to conversion between encodings and various other transformations. To represent a string of bytes, use NSData. (For instance, something like [NSData dataWithBytes:&myInteger length:sizeof(myInteger)].)

Chuck
Using `NSData` as shown above may not be sufficient. That line of code can have different effects on different hardware architectures due to endianness.
Chris Cleeland
Dealing with the raw bytes of a multibyte datatype is inherently tied to the hardware and its endianness.
Chuck