Bytewise reading of memory: “signed char *” vs “unsigned char *”

前端 未结 5 1464
一个人的身影
一个人的身影 2020-12-05 08:14

One often needs to read from memory one byte at a time, like in this naive memcpy() implementation:

void *memcpy(void *dest, const void *src, si         


        
5条回答
  •  盖世英雄少女心
    2020-12-05 08:45

    #include
    #include
    
    int main()
    {
    
    unsigned char a[4]={254,254,254,'\0'};
    unsigned char b[4];
    char c[4];
    
    memset(b,0,4);
    memset(c,0,4);
    
    memcpy(b,a,4);
    memcpy(c,a,4);
    int i;
    for(i=0;i<4;i++)
    {
        printf("\noriginal is %d",a[i]);
        printf("\nchar %d is %d",i,c[i]);
        printf("\nunsigned char %d is %d \n\n",i,b[i]);
    }
    
    }
    

    output is

    original is 254
    char 0 is -2           
    unsigned char 0 is 254 
    
    
    original is 254
    char 1 is -2
    unsigned char 1 is 254 
    
    
    original is 254
    char 2 is -2
    unsigned char 2 is 254 
    
    
    original is 0
    char 3 is 0
    unsigned char 3 is 0 
    

    so here char and unsign both have the same value so it doesnt matter in this case

    Edit

    if you read anything as signed char still in that case most highre bit will also going to copy so it doesnt matter

提交回复
热议问题