简体   繁体   中英

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. 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. (My computer is little endian and 64-bit)

I have the following code where my goal is to make encrypted2 match encrypted. 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.

Example input for encrypted[256] would be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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