Re: int to bytes(value in NSString)
Re: int to bytes(value in NSString)
- Subject: Re: int to bytes(value in NSString)
- From: Alastair Houghton <email@hidden>
- Date: Wed, 19 Aug 2009 11:47:15 +0100
On 19 Aug 2009, at 11:04, bosco fdo wrote:
Sorry if i am not clear.
But i need to group all binary format data together in my logic
for that i need to convert some integer to binary format(byte value?)
the below java code make the conversion correct
private byte[] int2bin(int i) {
byte[] value = new byte[4];
value[0] = (byte) ((i >>> 24) & 0xff);
value[1] = (byte) ((i >>> 16) & 0xff);
value[2] = (byte) ((i >>> 8) & 0xff);
value[3] = (byte) ((i) & 0xff);
return value;
}
Right. This *isn't* a string operation. NSString is for *strings* of
*characters*. NSString is *NOT* for storing bytes. It won't even
work for that in the general case (for instance because two-byte
sequences starting with values in the range 0xD8-0xDF will trigger
code for handling surrogate pairs, which will either result in errors
or strange behaviour).
You can either use an array of uint8_t values, in a similar way to
what you did in your Java code, or you can use an NSMutableData.
Also, for the usual set of word sizes, you can use the functions in
<libkern/OSByteOrder.h> to make your code simpler; e.g.
NSMutableData *myData = [NSMutableData dataWithLength:4];
uint32_t *pword = (uint32_t *)[myData mutableBytes];
*pword = OSSwapHostToBigInt32 (myNumber);
return myData;
Anyway, the entire problem seems to derive from the fact that you are
trying to misuse an NSString as a container of bytes. In Cocoa, it's
usual to use NSData (or NSMutableData) for the purpose you're
describing here.
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden