Re: NSString to bit pattern
Re: NSString to bit pattern
- Subject: Re: NSString to bit pattern
- From: Alastair Houghton <email@hidden>
- Date: Sat, 9 May 2009 00:21:06 +0100
On 8 May 2009, at 10:00, erappy wrote:
Hi, I am trying to find way to convert the NSString object into its
bit
pattern and convert that bit pattern into another NSString object,
For Example if I have
NSString *origStr = @"Hello":
NSString * bitPatternoforigStr ;
no I want to convert it to the bit pattern if Hello and return an
object of
type NSString with bit pattern.
it should be something like;
bitPatternoforigStr = @"0101101001100010010011111000010101100101" ;
Can someone help me in this.
You need to start by deciding what encoding you wish to use for your
string. NSString, broadly speaking, works as if it is a container for
UTF-16 code units. It isn't always implemented that way under the
covers, but you can assume that it behaves that way. If UTF-16 is
what you need, you could simply iterate over the string in a loop
doing something like this:
NSUInteger len = [myString length];
for (NSUInteger n = 0; n < len; ++n) {
unichar ch = [myString characterAtIndex:n];
// Turn ch (which is 16 bits in length) into binary and append it
to your result string
}
Often you might not want UTF-16 though, and in that case you can use
NSString's -dataUsingEncoding: method to convert the string to an
NSData containing data in the desired encoding. Then you might loop
over it differently, e.g.
#include <inttypes.h>
...
NSData *stringData = [myString
dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLen = [stringData length];
const uint8_t *bytes = (const uint8_t *)[stringData bytes];
for (NSUInteger n = 0; n < dataLen; ++n) {
// Turn bytes[n] into binary and append it to your result string
}
Converting an integer into a binary string is a trivial programming
exercise, so you should be able to do that part on your own.
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