0

我正在尝试将字节从 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';
4

1 回答 1

1

可能是因为s指向0的序列缺少 -terminator吗?charciphertext


更新:

代替

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';
于 2013-08-02T12:40:49.493 回答