簡體   English   中英

比較uint64_t和未簽名的字符*

[英]Comparing uint64_t with an unsigned char*

我有這個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;
}

我有一個unsigned char * (請注意末尾的空格!)和一個uint64_t ,我正在用來自unsigned char *的數據填充。

然后我memcmp都VAR和我期望得到0 ,但我得到-1 這是為什么?

我在想這與按位運算中c的提升方式有關,但我無法確切地找到問題所在。

如果使用此代碼:

#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;
}

我的機器上的輸出是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 

您可以看到存儲在內存中的字節被顛倒了。 這應該給您一個提示,如果您的PC是低位字節序,則i的最低有效字節''將存儲在內存地址的開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM