Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Convert char[] to NSString in Hex format

I have a problem I need to convert char [] to String, hexadecimal format

Example

Nsstring * result;
char[4]={0x01,0x02,0x03,0x04};

///    convert  --   char[] -> Nsstring in Hex format

Nslog(@"%@",result);

expected output: "01020304"

Thanks

like image 329
Slaxt Avatar asked Jul 11 '11 01:07

Slaxt


2 Answers

try this:

NSMutableString * result = [[NSMutableString alloc] init];
char cstring[4]={0x01,0x02,0x03,0x04};
///    convert  --   char[] -> Nsstring in Hex format
int i;
for (i=0; i<4; i++) {
    [result appendString:[NSString stringWithFormat:@"%02x",cstring[i]]];
}

NSLog(@"%@",result);
[result release];
like image 116
Michael Bai Avatar answered Nov 09 '22 05:11

Michael Bai


The formatter "%02x" will display an individual character as 2 digits of zero-padded hex. Simply loop though your array and build the string with them.

like image 35
cobbal Avatar answered Nov 09 '22 06:11

cobbal