我试图将nsdata中的字节转换为char *,但char *的长度大于nsdata的长度,并包含最后附加的额外垃圾字符。代码:
NSData * newData=[self dataFromHexString:trimmedHex];
NSLog(@"new data length %d",[newData length]);
char * ciphertext=(char*)[newData bytes];
NSLog(@"length of ciphertext %zd",strlen(ciphertext));
日志:
2013-08-02 17:02:28.175 AES[4187:11303] new data length 128
2013-08-02 17:02:28.176 AES[4187:11303] length of ciphertext 144
从早上开始坚持这一点。:(
const char * ciphertextTemp=(const char*)[newData bytes];
char ciphertext[[newData length]+1];
for (int len=0; len<[self length];len++) {
ciphertext[len]=ciphertextTemp[len];
}
ciphertext[[self length]]='\0';
答案 0 :(得分:1)
可能是0
- char
ciphertext
指向的序列缺少终结符吗?
<强>更新强>
而不是
for (int len=0; len<[self length];len++) {
ciphertext[len]=ciphertextTemp[len];
}
ciphertext[[self length]]='\0';
你可以这样做:
strncpy(ciphertext, ciphertextTemp, [newData length]);
ciphertext[[self length] - 1]='\0';