Objective c 如何将一个字符串转换成二进制,而空格保持不变?
对于我的应用程序,我想将NSString转换为包含二进制等价物的NSMutableString。所有空格必须放在适当的位置 我发现了一个将字符串转换为二进制的代码段,但不包括所有空格。大致是这样的:Objective c 如何将一个字符串转换成二进制,而空格保持不变?,objective-c,binary,space,converters,Objective C,Binary,Space,Converters,对于我的应用程序,我想将NSString转换为包含二进制等价物的NSMutableString。所有空格必须放在适当的位置 我发现了一个将字符串转换为二进制的代码段,但不包括所有空格。大致是这样的: NSMutableString *str2 = [NSMutableString stringWithFormat:@""]; for(NSInteger numberCopy = str; numberCopy > 0; numberCopy >>=1) { //Prep
NSMutableString *str2 = [NSMutableString stringWithFormat:@""];
for(NSInteger numberCopy = str; numberCopy > 0; numberCopy >>=1) {
//Prepend "0" or "1", depending on the bit
[str2 insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
Str为输入,str2为输出
对于包含空格的版本,我有一个数组,将输入字符串除以components separatedbystring:@“
,然后将二进制转换器片段(如上)除以每个数组对象。我把空格加进去
但是,我得到了控制台错误
***-[\uu NSArrayM objectAtIndex:]:索引2超出范围[0..1]
接下来是(尽管我认为这并不重要):
我想不出哪里出了问题,更不用说如何改变了
我的代码,str为输入,str2为输出:
//Convert to binary
NSMutableString *str2 = [NSMutableString stringWithFormat:@""];
int count = -1;
NSArray *array = [str componentsSeparatedByString: @" "];
NSUInteger numObjects = [array count];
//Converts each object of array into binary separately, so spaces remain intact.
while (1) {
++count;
NSString *string = array[count];
NSMutableString *mutStr = [NSMutableString stringWithFormat:@""];
for (NSInteger numberCopy = [string intValue]; numberCopy > 0; numberCopy >>=1) {
//Prepend "0" or "1", depending on the bit
[mutStr insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
if (numObjects != count + 1) {
//Add space if this is not last run through
[mutStr appendString: @" "];
} else break;
[str2 appendString: mutStr];
}
在循环中有两个位置,count
递增。
在任何情况下,都必须将mutStr
附加到str2
但我会使用for循环:
for (count = 0; count < numObjects; count++) {
NSString *string = array[count];
NSMutableString *mutStr = [NSMutableString stringWithFormat:@""];
for (NSInteger numberCopy = [string intValue]; numberCopy > 0; numberCopy >>=1) {
//Prepend "0" or "1", depending on the bit
[mutStr insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
[str2 appendString: mutStr];
if (numObjects != count + 1) {
//Add space if this is not last run through
[str2 appendString: @" "];
}
}
for(count=0;count0;numberCopy>>=1){
//根据位的不同,前置“0”或“1”
[mutStr insertString:((numberCopy&1)@“1”:@“0”)索引:0];
}
[str2-appendString:mutStr];
if(numObjects!=计数+1){
//如果这不是最后一次运行,请添加空间
[str2-appendString:@”“;
}
}
这是一个逻辑错误。在@Martin的部分之后,在最后一次运行中,else中断
位于调用[array count]
的部分之后,由于该计数索引处没有数组对象,程序中断
while (1) {
++count;
if (count == numbObjects)
break;
...
}
这肯定不会让我的代码工作,但不幸的是,这不是解决方案。在中编辑。@jazz14456:您的代码中有另一个错误,请参阅更新的答案。我同时也发布了:)。我会接受你的答案,因为你不是询问者,你做了关于
count+1
的第一部分,而不是++count
以及最后一个错误。在我接受之前,请将我的答案添加到你的答案中,因为没有该部分它将无法工作。@jazz14456:我现在添加了另一个同样有效的变体,而且在我看来更容易阅读。
while (1) {
++count;
if (count == numbObjects)
break;
...
}