简体   繁体   English

在C中将char数组转换为ULL时不匹配,反之亦然

[英]Mismatch when converting an char array into ULLs and vice versa in C

I have a huge 2048-bit string (string 'encrypted' of length 256 in example) it can take random values meaning NOT necessary ASCII values. 我有一个巨大的2048位字符串(例如,字符串“加密”的长度为256),它可以采用随机值,这意味着不必要的ASCII值。 My goal is to chunk it into unsigned long long (ULL) values to be used for some custom operation (which operates only on ULL) and restore back the original string from the chunked ULLs. 我的目标是将其分块为无符号的long long(ULL)值,以用于某些自定义操作(仅对ULL进行操作),然后从分块的ULL中恢复原始字符串。 (My computer is little endian and 64-bit) (我的计算机是Little Endian和64位)

I have the following code where my goal is to make encrypted2 match encrypted. 我有以下代码,我的目标是使加密的2匹配加密。 However the below code is incorrect. 但是,以下代码不正确。 I think it messes with endian-ness and so I do not get back the original string contents. 我认为它与字节序混乱,因此我没有找回原始的字符串内容。 Can anyone help me fix the issue or suggest a good work around? 谁能帮助我解决问题或提出解决方案?

unsigned long long val, longInt;
char buffer[9];
buffer[8] = '\0';
char byteArray[9];
byteArray[8] = '\0';

for(chunk = 0; chunk < 32; chunk++) {
    strncpy(buffer, encrypted + 8 * chunk, 8);
    val = (uint64_t)buffer[0] << 56 |
          (uint64_t)buffer[1] << 48 |
          (uint64_t)buffer[2] << 40 |
          (uint64_t)buffer[3] << 32 |
          (uint64_t)buffer[4] << 24 |
          (uint64_t)buffer[5] << 16 |
          (uint64_t)buffer[6] << 8  |
          (uint64_t)buffer[7];
    vals[chunk] = val;
}

for (chunk = 0; chunk < 32; chunk++) {
    longInt = vals[chunk];
    byteArray[0] = (char)((longInt >> 56) & 0xFF);
    byteArray[1] = (char)((longInt >> 48) & 0xFF);
    byteArray[2] = (char)((longInt >> 40) & 0xFF);
    byteArray[3] = (char)((longInt >> 32) & 0xFF);
    byteArray[4] = (char)((longInt >> 24) & 0xFF);
    byteArray[5] = (char)((longInt >> 16) & 0xFF);
    byteArray[6] = (char)((longInt >> 8) & 0xFF);
    byteArray[7] = (char)((longInt) & 0xFF);
    strncpy(encrypted2 + chunk * 8, byteArray, 8);
}

Please help me match encrypted and encrypted2 in my above code. 请帮助我在上面的代码中匹配加密和加密2。

Example input for encrypted[256] would be 加密[256]的示例输入为

C���EK�U�ߺA#|��-��fDJ�J
ڰ���.�2(��+<��^���r0��v�.�'��GR�M��,52�����{r7RPqRD1�ú
                                                          ��q4�iP��E�Cm��$
���Z�+�Q��&Xx�F0� X#(���N���6r�R�`�]"gvV2[)��75��)

使用char数组时,不使用字符串 :应该使用memcpy而不是strncpy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM