[英]Char to NSString ObjC
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myFile"];
NSData *bytes = [[NSData alloc] initWithContentsOfFile:filePath];
NSUInteger len = [bytes length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [bytes bytes], len);
NSMutableString *fileContents = [NSMutableString alloc] init];
for (int i = 0; i < len; i++) {
char curChar = byteData[i];
[fileContents appendString:[NSString stringWithFormat:@"%c", curChar]];
}
Putting a breakpoint right after char curChar = byteData[i]
, I see this: http://i.imgur.com/ryyi0Rw.png http://i.imgur.com/RaRQ7fu.png 在
char curChar = byteData[i]
之后放置一个断点,我看到了: http : char curChar = byteData[i]
http://i.imgur.com/RaRQ7fu.png
How do I append to fileContents
exactly what is shown in the image (\\x02, \\xd0 etc)? 我如何准确地附加到
fileContents
图像中显示的内容(\\ x02,\\ xd0等)? Currently all I get are weird characters like Ð 目前我得到的都是奇怪的字符,例如Ð
I've seen a lot of questions about how to convert a char to NSString but nothing does what I want... 我已经看到了很多有关如何将char转换为NSString的问题,但是我没有想要的东西...
Use a different format: 使用其他格式:
[fileContents appendString:[NSString stringWithFormat:@"\\x%02x", (unsigned)curChar]];
EDIT: To save typing you can use appendFormat:
(as pointed out in the now deleted answer from Nikolai Ruhe). 编辑:要保存键入,您可以使用
appendFormat:
如从Nikolai Ruhe现在删除的答案中指出的那样)。
If you mean you want literally backslash-x-0-2, then see @trojanfoe's answer. 如果您是说要字面反斜杠-x-0-2,请参阅@trojanfoe的答案。 If you mean you want "the character with value 2," then read on.
如果您要使用“值为2的字符”,请继续阅读。
What encoding is the file in? 文件采用什么编码? You can't talk about a string without considering its encoding.
您不能不考虑字符串的编码就谈论它。 If it's "just a string of bytes" then that isn't an
NSString
; 如果它只是“一串字节”,那不是
NSString
; it's an NSData
and should be treated that way. 这是一个
NSData
,应该以这种方式对待。
Once you know the encoding, then you shouldn't need the NSData
step. 知道编码后,就不需要
NSData
步骤了。 Just use [NSString stringWithContentsOfFile:encoding:error:]
. 只需使用
[NSString stringWithContentsOfFile:encoding:error:]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.