从nsdata获取字节会附加额外的垃圾字符

时间:2013-08-02 11:22:26

标签: ios objective-c c pointers nsdate

我试图将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';

1 个答案:

答案 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';