I want to concatenate null characters with regular characters like so:
NSString *message = @"ABC";
NSUInteger length = [message length];
char char4 = length;
char char3 = length >> 8;
char char2 = length >> 16;
char char1 = length >> 24;
message = [NSString stringWithFormat:@"%c%c%c%c%@",char4,char3,char2,char1,message];
The problem is that the string stays at length 4 (and looks like ¿ABC). How can I edit this code so that the null characters are also appended to the string?
In reply to Mark’s comment
What I am trying to do here is append the length of the string to the beginning of the string, not in numerical format, but in the format of ascii characters (almost like a base 256 number). I would use the format, @"%04c%@",length,message, the problem is that the resulting string would be 000¿ABC and zeroes have ascii value (48 in decimal to be exact) and so that defeats the purpose. The ASCII character that has decimal value 0 is the null character (\0) so I have to use that instead of 0. It is necessary that I have those leading null characters.
For the purposes of what I’m trying to accomplish, the following code works
NSUInteger length = [message length];
char char4 = length;
char char3 = length >> 8;
char char2 = length >> 16;
char char1 = length >> 24;
if (char4 == '\0')
message = [NSString stringWithFormat:@"\0%@",message];
else
message = [NSString stringWithFormat:@"%c%@",char4,message];
if (char3 == '\0')
message = [NSString stringWithFormat:@"\0%@",message];
else
message = [NSString stringWithFormat:@"%c%@",char3,message];
if (char2 == '\0')
message = [NSString stringWithFormat:@"\0%@",message];
else
message = [NSString stringWithFormat:@"%c%@",char2,message];
if (char1 == '\0')
message = [NSString stringWithFormat:@"\0%@",message];
else
message = [NSString stringWithFormat:@"%c%@",char1,message];
But, if anybody can contribute something shorter or more intuitive, that’d be great.
Don’t do this. It’s a bad idea. For example, NSString is conceptually built on 16-bit Unicode characters, but you’re trying to prepend bytes. Note that there’s nothing guaranteeing that NSString’s internal representation is UTF-16 or any other specific encoding. In any case, when the string is written out it has to be converted to whatever encoding and that is unlikely to preserve your length prefixing in a way you can predict.
Use an NSData with the length in the first 4 (or maybe 8 would be better for a 64-bit length) bytes followed by the string in a particular encoding. I recommend UTF-8.