Objective-C,如何正确地将十六进制编码为图像文件? [英] Objective-C, How to properly encode hex to image file?
问题描述
我在我的应用程序中有一个方法,我想将十六进制值写入文件(实际上是从写入的字节创建一个映像)。我似乎无法弄清楚如何正确编码值来生成图像。任何建议,将不胜感激 - 谢谢。
- (void)makeImage {
@autoreleasepool {
NSString * hexValues = @8950 ...//这些是组成图像文件的十六进制字节
NSString * fileName = @image.png;
NSString * homeDir = [NSHomeDirectory()stringByAppendingPathComponent:@Desktop /];
NSString * fullPath = [homeDir stringByAppendingPathComponent:fileName];
NSError * error = nil;
[lastLine writeToFile:完整路径原子化:NO编码:NSASCIIStringEncoding错误:& error];
使用有损ASCII编码或UTF-8转换NSData中的NSString,然后您可以使用方法 - [NSData bytes]来获取原始字节。
使用for循环一次循环遍历2个字节,然后可以将您要上传的两个字节/字符复制到大小为3的char数组中(3包含\0,请确保使用00 来终止\0)然后你可以使用c函数
$ p $ long c ++ strtol(const char * str,char ** endptr,int base);
将两个字节/十六进制转换为整数。
或者你可以写你自己的十六进制字符串为int,不需要终止\0。
I have a method in my app that I would like to write hex values into a file (essentially creating an image from the written bytes). I can't seem to figure out how to encode the values properly to produce the image. Any suggestion would be appreciated - thanks.
- (void)makeImage {
@autoreleasepool {
NSString* hexValues = @"8950..." // these are the hex bytes that make up the image file
NSString* fileName = @"image.png";
NSString* homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/"];
NSString* fullPath = [homeDir stringByAppendingPathComponent:fileName];
NSError* error = nil;
[lastLine writeToFile:fullPath atomically:NO encoding:NSASCIIStringEncoding error:&error];
}
You can convert the NSString in an NSData with lossy ASCII encoding or UTF-8, then you can use the method -[NSData bytes] to get to the raw bytes.
Use a for loop to loop through them 2 bytes at a time, you can then either copy the two bytes/characters you are upto into a char array of of size 3 (3 to include the \0, make sure you initialize it with "00" to get a terminating \0) you can then use the c function
long int strtol ( const char * str, char ** endptr, int base );
to convert the two bytes/hex to an integer.
Alternatively you can write your own hex-string to int that doesn't require a terminating \0.
这篇关于Objective-C,如何正确地将十六进制编码为图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!