如何在Objective-C中将十六进制字符串(NSString)转为字节数组及NSArray
Hey there! Making the jump from Java/Android to iOS is a fun (and sometimes tricky) transition—let's sort out how to convert that hex string into the exact NSArray you're looking for, and also take a look at your current method to spot any issues.
First, Let's Break Down Your Goal
You have a hex string:
NSString *code = @"11111bfb";
And you want to convert it to an NSArray of NSNumber objects representing each byte:
NSArray *codeArray = @[@0x11, @0x11, @0x1b, @0xfb];
Looking at Your Existing Method
Your current dataFromHexString: method returns an NSData object, which is great for raw byte storage—but it doesn't directly give you the NSArray of NSNumbers you need. Additionally, there's a small issue with how it handles odd-length strings:
- When the string length is odd, you prepend
@"0x", butstrtoultreats0xas a prefix for hex values, not as actual hex digits. This means for an odd-length string like@"1bfb", your code would turn it into@"0x1bfb"and then parse the first two characters ("0x") as0, which isn't the correct way to pad the string (you should prepend a single0instead).
The Correct Implementation for Your Needs
Here's a method that directly converts your hex string into the NSArray of NSNumber objects you're targeting:
- (NSArray<NSNumber *> *)hexStringToNumberArray:(NSString *)hexString { // Remove any spaces from the input string (in case they exist) hexString = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""]; NSUInteger stringLength = hexString.length; // Pad with a leading 0 if the string length is odd (so we can process in pairs) if (stringLength % 2 != 0) { hexString = [@"0" stringByAppendingString:hexString]; stringLength += 1; } NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:stringLength / 2]; // Iterate over the string two characters at a time for (NSUInteger i = 0; i < stringLength; i += 2) { NSString *byteSubstring = [hexString substringWithRange:NSMakeRange(i, 2)]; NSScanner *scanner = [NSScanner scannerWithString:byteSubstring]; unsigned int byteValue; // Parse the two-character hex substring into an integer [scanner scanHexInt:&byteValue]; // Add the byte value as an NSNumber to the array // If you need signed bytes, cast to int8_t here: @((int8_t)byteValue) [resultArray addObject:@(byteValue)]; } return resultArray; }
How to Use It
Call it with your example string:
NSString *code = @"11111bfb"; NSArray *codeArray = [self hexStringToNumberArray:code]; // codeArray will be @[@0x11, @0x11, @0x1b, @0xfb]—exactly what you want!
Key Improvements Over Your Original Method
- Directly returns the NSArray type you need: No extra steps to convert from NSData to an array of NSNumbers.
- Correct padding for odd-length strings: Prepends a single
0instead of0x, ensuring valid hex digit pairs. - Uses NSScanner for safe parsing: It's a more Objective-C-native way to handle hex conversion and avoids potential issues with C string manipulation.
内容的提问来源于stack exchange,提问作者Edward Tattsyrup

