내 앱의 경우 NSString을 NSMutableString으로 변환하고 싶습니다. 모든 칸은 적절한 자리에 있어야합니다.문자열을 바이너리로 공백으로 변환하기
문자열을 바이너리로 변환하는 스 니펫을 발견했지만 모든 공백은 제외되었습니다. 이것은 다소 비슷하게 보입니다 :
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가 출력됩니다.
공백이 포함 된 버전의 경우 입력 문자열을 componentsSeparatedByString: @" "
으로 나눈 다음 이진 변환기 스 니펫 (위)을 각 배열 개체로 나눕니다. 나는 다시 공간을 추가
을 (나는 그것의 중요한 생각하지 않지만) 그러나, 나는이 다음에 콘솔 오류
*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]
를 얻을 :.
0 CoreFoundation 0x00007fff84a08b06 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff8c72f3f0 objc_exception_throw + 43
2 CoreFoundation 0x00007fff849a58ec -[__NSArrayM objectAtIndex:] + 252
3 G-Clock 0x0000000100001ff1 -[GCAppController tick:] + 1937
4 Foundation 0x00007fff8a011d05 __NSFireDelayedPerform + 358
5 CoreFoundation 0x00007fff849c5804 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
6 CoreFoundation 0x00007fff849c531d __CFRunLoopDoTimer + 557
7 CoreFoundation 0x00007fff849aaad9 __CFRunLoopRun + 1529
8 CoreFoundation 0x00007fff849aa0e2 CFRunLoopRunSpecific + 290
9 HIToolbox 0x00007fff83bbdeb4 RunCurrentEventLoopInMode + 209
10 HIToolbox 0x00007fff83bbdb94 ReceiveNextEventCommon + 166
11 HIToolbox 0x00007fff83bbdae3 BlockUntilNextEventMatchingListInMode + 62
12 AppKit 0x00007fff88b7a533 _DPSNextEvent + 685
13 AppKit 0x00007fff88b79df2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
14 AppKit 0x00007fff88b711a3 -[NSApplication run] + 517
15 AppKit 0x00007fff88b15bd6 NSApplicationMain + 869
16 G-Clock 0x0000000100000ea2 main + 34
17 libdyld.dylib 0x00007fff864fc7e1 start + 0
18 ??? 0x0000000000000003 0x0 + 3
)
내가 할 수있는 무엇이 잘못 되었습니까? 변경하는 방법은 말할 것도 없습니다. 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];
}
그건 분명히 내 코드를 작동시키지 못했지만, 불행히도 해결책이 아니 었습니다. –
@ jazz14456 : 코드에 다른 오류가 있습니다 (업데이트 된 답변 참조). –
나는 그것을 동시에 게시했다 :). 나는 너의 것을 받아 들일 것이다 왜냐하면 너는 묻지 않고 너는 마지막 오류 –