1

In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};

How to convert my NSString to char byte array like this one?

Thanks!

8
  • check this stackoverflow.com/questions/11087031/… Commented Mar 29, 2017 at 8:02
  • You want to get each individual char bytes or char? Commented Mar 29, 2017 at 8:08
  • @MianShahbazAkram in my example String, I would like "AA" to give the result "0xAA" as a byte that I can pass in my char array. Commented Mar 29, 2017 at 8:15
  • @fraxool bro i have updated answer check if its working for you.. Commented Mar 29, 2017 at 8:22
  • @Mukesh I saw your answer which gave an "out of bounds" error... Commented Mar 29, 2017 at 9:06

4 Answers 4

1
 NSString *strCharData = @"AA010158AA7D385002";
 const char *characterRes = [strCharData cStringUsingEncoding:NSUTF8StringEncoding]; 

      or

 NSString *strCharData = @"AA010158AA7D385002";
 const char *characterRes = [strCharData UTF8String]; 
Sign up to request clarification or add additional context in comments.

Comments

0

Use this answer if i am correct,i did little coding but might be there are possibilities of simpler solutions also like @user3182143

NSString * inputStr = @"AA010158AA7D385002";
NSMutableArray *charByteArray = [[NSMutableArray alloc]initWithCapacity:1];
int i = 0;
for (i = 0; i+2 <= inputStr.length; i+=2) {

    NSRange range = NSMakeRange(i, 2);
    NSString* charStr = [inputStr substringWithRange:range];
    [charByteArray addObject:[NSString stringWithFormat:@"0x%@",charStr]];

}

Output :

char[9] = ( 0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02 )

6 Comments

That wouldn't give a char[9] like the OP asked, that would give an NSArray<NSString*>.
@uliwitness What it mean NSArray<NSString> can you explain me please ? You know we can convert it into NSArray by copy & it will also gives same output. :D
@Mukesh if you can update your answer with the output as a char[9], I will accept your answer.
@fraxool welcome :) but we have 9 array object that mean 0..8 index, good luck
@fraxool accept & up my answer if it helps for you.
|
0

Since your text is hex and you want actual bytes out (which each correspond to two hex characters), you'll have to manually convert each character into the corresponding number, and then add them together into the correct numerical value.

To do this, I'm taking advantage of the fact that, in ASCII characters, a...z are in a row, as are 0...9. I'm also taking advantage of the fact that hexadecimal is valid ASCII, and that Unicode characters from 0...127 are identical to their corresponding ASCII characters.

Below is a program that does this and prints out the original string's characters as well as the calculated bytes (as hex again):

#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        NSString *hexStr = @"1234567890abcdef12";
        unsigned char theBytes[9] = {};
        for( NSUInteger x = 0; x < sizeof(theBytes); x++ )
        {
            unsigned char digitOne = [hexStr characterAtIndex: x * 2];
            if( digitOne >= 'a' )
                digitOne -= 'a' -10;
            else
                digitOne -= '0';
            unsigned char digitTwo = [hexStr characterAtIndex: (x * 2) +1];
            if( digitTwo >= 'a' )
                digitTwo -= 'a' -10;
            else
                digitTwo -= '0';
            printf("%01x%01x",digitOne,digitTwo);
            theBytes[x] = (digitOne << 4) | digitTwo;
        }
        printf("\n");

        for( int x = 0; x < sizeof(theBytes); x++ )
            printf("%02x",theBytes[x]);
        printf("\n");
    }
}

Note: This code naïvely assumes that you are providing a correct string. I.e. your input has to consist of lowercase characters and numbers only, and exactly 18 characters. Anything else and you get a wrong result or an exception.

Comments

0

I finally managed to find the answer to my own question. I am posting it here in case it helps someone else.

So I use a method to convert an NSString hex to bytes :

@implementation NSString (HexToBytes)

    - (NSData *)hexToBytes
    {
        NSMutableData   *data = [NSMutableData data];
        int             idx;

        for (idx = 0; idx + 2 <= self.length; idx += 2) {
            NSRange         range = NSMakeRange(idx, 2);
            NSString        *hexStr = [self substringWithRange:range];
            NSScanner       *scanner = [NSScanner scannerWithString:hexStr];
            unsigned int    intValue;
            [scanner scanHexInt:&intValue];
            [data appendBytes:&intValue length:1];
        }

        return data;
    }

@end

And then, I simply use it like that :

NSString *str = @"AA010158AA7D385002";
NSData *databytes = [str hexToBytes];
char *bytePtr = (char *)[databytes bytes];

And I finally get my char array. Hope it helps someone else.

1 Comment

This helped me instead of this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.