我正在尝试将一行十六进制转换为一行 char 值。这是我使用的代码:
// Store HEX values in a mutable string:
NSUInteger capacity = [data length] * 2;
NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
const unsigned char *dataBuffer = [data bytes];
NSInteger i;
for (i=0; i<[data length]; ++i) {
[stringBuffer appendFormat:@"%02X ", (NSUInteger)dataBuffer[i]];
}
// Log it:
NSLog(@"stringBuffer is %@",stringBuffer);
// Convert string from HEX to char values:
NSMutableString * newString = [[NSMutableString alloc] init];
NSScanner *scanner = [[NSScanner alloc] initWithString:content];
unsigned value;
while([scanner scanHexInt:&value]) {
[newString appendFormat:@"%c ",(char)(value & 0xFF)];
}
NSLog(@"newString is %@", newString);
到目前为止,这很好用。输出按预期收到:
String Buffer is 3D 3E 2C 01 2C 31 33 30 37 31 38 30 39 32 34 2D 30 37 2C FF 00 00 00 00 00
newString is = > , , 1 3 0 7 1 8 0 9 2 4 - 0 7 , ˇ
只有一个问题,NULL 值正在终止我的字符串(我认为)。新字符串应该输入“0 0 0 0”,但它没有,它只是在那里结束。我认为它在那里结束,因为连续 3 个零 = char 中的 NULL。有谁知道我如何防止这个字符串终止并显示整个值?