Wingzero Wingzero - 11 days ago 5
Objective-C Question

error: hex escape sequence out of range

Trying to compare to a string:

BOOL r = [res isEqualToString:[@"\x124Vx\xc3\xaa"]];


However I got


error: hex escape sequence out of range


I tried also something like:

NSString *s = [@"\x12" stringByAppendingString: @"4Vx\xc3\xaa"];
BOOL r = [res isEqualToString:s];


Now it could work and return
YES


How can I specify such string and avoiding splitting them up first? It's kind of annoying...

UPDATE:
I use @rmaddy's code, and it works now, however, If I put it in array like:

NSArray *answers = @[
@"",
@"#",
@"\x12""4Vx\xc3\xaa",
]


It will generate a warning for the last string literal:


Concatenated NSString literal for an NSArray expression - possibly missing a comma
How to get rid of it?


Using

NSString *s = @"\x12""4Vx\xc3\xaa";
NSArray *arr = @[s];


Can work, but I prefer not writing more NSString *s ... to do it.

Answer

The problem with:

BOOL r = [res isEqualToString:@"\x124Vx\xc3\xaa"];

is with the \x124 part. It seems you can only have hex values in the range 00 - ff. And note the removal of the [ ] around the string.

If you don't want the 4 to be considered part of the \x hex number, you can do this:

BOOL r = [res isEqualToString:@"\x12""4Vx\xc3\xaa"];

The two double-quote characters ensure the \x escape sequence stops where you need it to.

To eliminate the new warning about a possible missing comma when using such a string in an NSArray, you will need to use the older syntax to create the array:

NSArray *answers = [NSArray arrayWithObjects:
                     @"",
                     @"#",
                     @"\x12""4Vx\xc3\xaa",
                     nil
                     ];