123
123

Reputation: 5824

Hex NSString to char[]

I have a hex NSString and I want to be able to pack that to a char array.

For example, I have a NSString:

NSString* hex = "AABBCCDD";

and I want to be able to convert that to a char array for use with CCCrypt:

char bytes[] = { 0xAA, 0xBB, 0xCC, 0xDD };

How could I do this?

Upvotes: 3

Views: 3522

Answers (3)

Alex Nichol
Alex Nichol

Reputation: 7510

You can use a for loop to go through each two byte hexadecimal character. Then, use NSScanner to read it into a char variable for your character array.

NSString * hexString = @"AABBCCDD";
char * myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
    unsigned int anInt;
    NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
    NSScanner * scanner = [[[NSScanner alloc] initWithString:hexCharStr] autorelease];
    [scanner scanHexInt:&anInt];
    myBuffer[i / 2] = (char)anInt;
}
...
// use myBuffer here
...
printf("%s\n", myBuffer);
free(myBuffer);

Note that this will only work if hexString has an even length (i.e. divisible by two).

Upvotes: 8

Thomas K
Thomas K

Reputation: 6196

I think you could use something like this:

const char* cString = [hex UTF8String]; 

Upvotes: -1

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

Something like this should work....

NSScanner *scanner = [NSScanner scannerWithString:@"AABBCCDD"];
uint32_t hex;
[scanner scanHexInt:&hex];
char bytes[] = {(hex >> 24)  & 0xFF, (hex >> 16) & 0xFF, (hex >> 8) & 0xFF, hex & 0xFF};

Untested as I did it in the browser.

Upvotes: 2

Related Questions