I need to convert a Hex String to encoded binary data (not 010101 ), a function equivalent of hex2bin of php http://php.net/manual/en/function.hex2bin.php
2
-
1possible duplicate of How to convert Hex to Binary iphoneYogesh Suthar– Yogesh Suthar2015-04-06 10:04:42 +00:00Commented Apr 6, 2015 at 10:04
-
1I don't need Binary string (e.g 010101), I need something equivalent of php pack function,user12334– user123342015-04-07 06:07:47 +00:00Commented Apr 7, 2015 at 6:07
Add a comment
|
2 Answers
I found this through google in case someone is looking:
-(NSData *) CreateDataWithHexString:(NSString *)inputString
{
NSUInteger inLength = [inputString length];
unichar *inCharacters = alloca(sizeof(unichar) * inLength);
[inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];
UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));
NSInteger i, o = 0;
UInt8 outByte = 0;
for (i = 0; i < inLength; i++) {
UInt8 c = inCharacters[i];
SInt8 value = -1;
if (c >= '0' && c <= '9') value = (c - '0');
else if (c >= 'A' && c <= 'F') value = 10 + (c - 'A');
else if (c >= 'a' && c <= 'f') value = 10 + (c - 'a');
if (value >= 0) {
if (i % 2 == 1) {
outBytes[o++] = (outByte << 4) | value;
outByte = 0;
} else {
outByte = value;
}
} else {
if (o != 0) break;
}
}
return [[NSData alloc] initWithBytesNoCopy:outBytes length:o freeWhenDone:YES];
}
Comments
You can do so by-
- (NSString*)convertHexToBinary:(NSString*)hexString
{
NSMutableString *returnString = [NSMutableString string];
for(int i = 0; i < [hexString length]; i++)
{
char c = [[hexString lowercaseString] characterAtIndex:i];
switch(c) {
case '0': [returnString appendString:@"0000"]; break;
case '1': [returnString appendString:@"0001"]; break;
case '2': [returnString appendString:@"0010"]; break;
case '3': [returnString appendString:@"0011"]; break;
case '4': [returnString appendString:@"0100"]; break;
case '5': [returnString appendString:@"0101"]; break;
case '6': [returnString appendString:@"0110"]; break;
case '7': [returnString appendString:@"0111"]; break;
case '8': [returnString appendString:@"1000"]; break;
case '9': [returnString appendString:@"1001"]; break;
case 'a': [returnString appendString:@"1010"]; break;
case 'b': [returnString appendString:@"1011"]; break;
case 'c': [returnString appendString:@"1100"]; break;
case 'd': [returnString appendString:@"1101"]; break;
case 'e': [returnString appendString:@"1110"]; break;
case 'f': [returnString appendString:@"1111"]; break;
default : break;
}
}
return returnString;
}
3 Comments
user12334
This is not what I am looking for Binary data as in content of binary file like "exe"
Vette
It was exactly what "I" was looking for though. Thanks!
Sanjay Mohnani
@Vette Welcome Vette!