Take the 2-minute tour ×

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


Nsstring * result;

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


expected output: "01020304"


share|improve this question
Well, what have you tried? –  Jonathan Grynspan Jul 11 '11 at 1:47
add comment

2 Answers

up vote 6 down vote accepted

try this:

NSMutableString * result = [[NSMutableString alloc] init];
char cstring[4]={0x01,0x02,0x03,0x04};
int i;
    [result appendString:[NSString stringWithFormat:@"%02x",cstring[i]]];

[result release];
share|improve this answer
+1, but it would be better to use initWithCapacity: to avoid reallocations, since you know how long the string is going to be. –  Adam Rosenfield Jul 11 '11 at 2:24
Then you probably would also want to do [result appendFormat:@"%02x",cstring[i]]; to avoid the extra string allocation. –  Jon Hess Jul 11 '11 at 4:51
If you need uppercase, and all 3 in a row, like I do, "%02X%02X%02X" is the correct string for that. –  SilverSideDown Oct 1 '12 at 14:26
add comment

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.

share|improve this answer
add comment

Your Answer


