简体   繁体   English

比较uint64_t和未签名的字符*

[英]Comparing uint64_t with an unsigned char*

I have this POC 我有这个POC

#include <stdio.h>
#include <stdint.h>

int main(void) {
    unsigned char *c = "This is ";
    uint64_t i;
    int j;
    i = c[7] | (c[6] << 8) | (c[5] << 16) | (c[4] << 24) | (c[3] << 32) | (c[2] << 40) | (c[1] << 48) | (c[0] << 56);
    printf("c value: '%s'\n", c);
    printf("Hex:");
    for (j = 0; j < 8; j++) {
        printf(" %2x", c[j]);
    }
    printf("\n");

    printf("Is i equal to c? %d\n", 
        memcmp((unsigned char *)&i, "\x54\x68\x69\x73\x20\x69\x73\x20", 8)
    );
    return 0;
}

I have an unsigned char * (please note the white space at the end!) and an uint64_t which I'm filling in with the data from the unsigned char * . 我有一个unsigned char * (请注意末尾的空格!)和一个uint64_t ,我正在用来自unsigned char *的数据填充。

Then I memcmp both vars and I'd expect to get 0 , but I get -1 . 然后我memcmp都VAR和我期望得到0 ,但我得到-1 Why is that? 这是为什么?

I'm thinking it has something to do with how c is promoted in the bitwise operations, but I can't find exactly what is going wrong. 我在想这与按位运算中c的提升方式有关,但我无法确切地找到问题所在。

If you take this code: 如果使用此代码:

#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main(void) {
    unsigned char *c = "This is ";
    uint64_t i;
    int j;
    i = (uint64_t ) c[7] | ((uint64_t )c[6] << 8) | ((uint64_t )c[5] << 16) | ((uint64_t )c[4] << 24) | ((uint64_t )c[3] << 32) | ((uint64_t )c[2] << 40) | ((uint64_t )c[1] << 48) | ((uint64_t )c[0] << 56);
    printf("c value: '%s'\n", c);
    printf("Hex:");
    for (j = 0; j < 8; j++) {
        printf(" %2x", c[j]);
    }
    printf("\n");

    printf("Printing i contents as they appear in memory \n");
    unsigned char *k=(unsigned char*)&i;
    for(int j = 0;j<8 ;j++)
        printf("%2x ",(unsigned) k[j]);
    printf("\n");

    printf("Is i is equal to c? %d\n",
           memcmp(&i, "\x54\x68\x69\x73\x20\x69\x73\x20", 8)
           );
    return 0;
}

The output on my machine which is little endian is: 我的机器上的输出是Little Endian:

    c value: 'This is '
    Hex: 54 68 69 73 20 69 73 20
    Printing i contents as they appear in memory 
    20 73 69 20 73 69 68 54 

You can see the bytes are reversed when stored in memory. 您可以看到存储在内存中的字节被颠倒了。 This should give you clue that if your PC is little endian, i 's least significant byte which is ' ' will be stored at the beginning in the memory address. 这应该给您一个提示,如果您的PC是低位字节序,则i的最低有效字节''将存储在内存地址的开头。

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

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