Store content of a buffer in a NSString
Good evening,
I wrote the code below in C to read and print from a binary file a random hexa开发者_StackOverflow社区decimal string with a constant length, knowing a certain offset and the location of the string regarding the offset.
FILE *f = NULL;
unsigned char *buffer = NULL;
unsigned long fileLen;
unsigned char bytes[] = {0x22, 0x22, 0x22, 0x22};
f = fopen(argv[1], "rb");
if (!f)
{
fprintf(stderr, "Unable to open %s\n", argv[1]);
return -1;
}
fseek(f, 0, SEEK_END);
fileLen=ftell(f);
fseek(f, 0, SEEK_SET);
buffer=malloc(fileLen);
if (!buffer)
{
fprintf(stderr, "Memory error!\n");
fclose(f);
return -1;
}
fread(buffer, fileLen, 1, f);
fclose(f);
unsigned int *p = memmem(buffer, fileLen, bytes, 4);
if (!p) {
return -1;
}
unsigned long off_to_string = 4 + 0x12 + ((void *)p) - ((void *)buffer);
for (unsigned long c = off_to_string; c < off_to_string+0x30; c++)
{
printf("%.2X", (int)buffer[c]);
}
printf("\n");
free(buffer);
I would like to use this code in a Cocoa app, I tried to make something like:
NSMutableString *tehString = [[NSMutableString alloc] init];
for (unsigned long c = off_to_string; c < off_to_string+0x30; c++)
{
[tehString appendString:...]
}
the problem is I must pass a NSString to appendString:
and I don't even know how to print its hexadecimal representation.
Thanks !
PS: Feel free to improve the code of the "hexadecimal string reader" :)
NSStrings can be created using the same string format specifiers.
so you could do this:
[tehString appendString:[NSString stringWithFormat:@"%.2X", (int)buffer[c]]];
caveat: I've just typed that in so it might be a little off - but you get the idea.
精彩评论