本文介绍了转换"弦乐"二进制到文字的NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能够一个NSString转换(ASCII)文本二进制数的NSString,但我有麻烦做相反。例如:你好变成01101000 01101001
I am able to convert an NSString of (ASCII) text to a NSString of binary numbers, but I am having troubles doing the opposite. For example: "Hi" becomes "01101000 01101001".
I need: "01101000 01101001" to become "Hi".
我在寻找最实施这种直接的方式。注意二进制数的每8位之间的空间。
I'm looking for the most direct way to implement this. Note the space between every 8 bits of binary numbers.
推荐答案
考虑到格式的总是的那样,这code应该工作:
Considering the format is always like that, this code should work:
NSString *
BinaryToAsciiString (NSString *string)
{
NSMutableString *result = [NSMutableString string];
const char *b_str = [string cStringUsingEncoding:NSASCIIStringEncoding];
char c;
int i = 0; /* index, used for iterating on the string */
int p = 7; /* power index, iterating over a byte, 2^p */
int d = 0; /* the result character */
while ((c = b_str[i])) { /* get a char */
if (c == ' ') { /* if it's a space, save the char + reset indexes */
[result appendFormat:@"%c", d];
p = 7; d = 0;
} else { /* else add its value to d and decrement
* p for the next iteration */
if (c == '1') d += pow(2, p);
--p;
}
++i;
} [result appendFormat:@"%c", d]; /* this saves the last byte */
return [NSString stringWithString:result];
}
告诉我,如果它的某些部分是不清楚。
Tell me if some part of it was unclear.
这篇关于转换"弦乐"二进制到文字的NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!