Question

How do I convert a series of 32 bits (representing 4 bytes) stored in an NSString, into an NSData object of 4 bytes in objective-c?

For example, how can I convert the following string:

NSString *bitSeries = @"00000000000000000000000111101100";

into NSData object with length precisely 4?

Was it helpful?

Solution

You can use strtoul() with base 2 to convert the string to an unsigned integer:

NSString *bitSeries = @"00000000000000000000000111101100";
uint32_t value = strtoul([bitSeries UTF8String], NULL, 2);

and then create an NSData object:

NSData *data = [NSData dataWithBytes:&value length:sizeof(value)];
NSLog(@"%@", data);
// Output: <ec010000>

Or, if you prefer big-endian byte order:

value = OSSwapHostToBigInt32(value);
NSData *data = [NSData dataWithBytes:&value length:sizeof(value)];
NSLog(@"%@", data);
// Output: <000001ec>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top