objective-c - 将缓冲区的内容存储在 NSString 中

标签 objective-c c memory

晚上好,

我用 C 语言编写了下面的代码,从二进制文件中读取并打印一个具有恒定长度的随机十六进制字符串,知道某个偏移量以及与该偏移量相关的字符串的位置。

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);

我想在 Cocoa 应用程序中使用此代码,我尝试制作如下内容:

NSMutableString *tehString = [[NSMutableString alloc] init];

for (unsigned long c = off_to_string; c < off_to_string+0x30; c++)
{
    [tehString appendString:...]
}

问题是我必须将 NSString 传递给 appendString: 并且我什至不知道如何打印其十六进制表示形式。

谢谢!

PS:随意改进“十六进制字符串读取器”的代码:)

最佳答案

NSString 可以使用相同的 string format specifiers 创建.

所以你可以这样做:

[tehString appendString:[NSString stringWithFormat:@"%.2X", (int)buffer[c]]];

警告:我刚刚输入了这个内容,所以可能有点不对劲 - 但你明白了。

关于objective-c - 将缓冲区的内容存储在 NSString 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7296351/

相关文章:

c - 128 位整数乘法

ios - 如何在 iOS 上监听 View 的框架属性

iphone - 使用 NSDictionary 的崩溃错误 - Iphone SDK

ios - 使用 NSPredicate IOS 取反值

c - C 程序中的 Shellcode

c - 如何使 Gtk+ 窗口背景透明?

c - 为什么我的二进制更新打印乱码/垃圾而不是我插入的信息?

c++ - 在 Visual Studio 中模拟一个简单的内存泄漏,结果有点困惑

objective-c - [self self] 在 objective c 中是什么意思?

c++ - 结构尺寸定义