an error not easily discovered

来源:互联网 发布:知乎 马三娘你凭啥骑马 编辑:程序博客网 时间:2024/06/04 19:59

The following code is convert byte to hex.

When code is writed like 1,  when text[i]'s high nibble byte

=F,  it will cause htext[i]=0x00, i.e., null.

Therefore, it will produce wrong result.


The cause is that the compiler first does signed extend against text[i],

if text[i]'s high nibble byte=F, assume it 0xF5, the signed extend will let

it 0xFFFFFFF5, the shift right 4 bits, this will lead to 0XFFFFFFFF;

Therefore, hex[(text[i] >> 4)] will be hex[0xFFFFFFFF], it will produce 0,

or null, or segment fault. andhex[(text[i] & 0x0f)] = hex[0x0F] = 'F'


The correct code is write like 2.


1.

void hex_dump(char *text, char *htext, int len)

{
    int i = 0;

    static char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    for(i = 0; i < len; i++) {
        htext[2 * i] = hex[(text[i] >> 4)];
        htext[2 * i + 1] = hex[(text[i] & 0x0f)];
    }

    key[len * 2] = 0x00;

    return;
}


2.

void hex_dump(unsigned char *text, unsigned char *htext, int len)
{
    int i = 0;

    static char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    for(i = 0; i < len; i++) {
        htext[2 * i] = hex[(text[i] >> 4)];
        htext[2 * i + 1] = hex[(text[i] & 0x0f)];
    }

    key[len * 2] = 0x00;

    return;
}

原创粉丝点击