Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Why does using char math result in unexpected results in C++?

I have a function that I am having a hard time understanding how the math is being performed:

    unsigned long Fat_AuthAnswer(char b1, char b2, char b3, char b4)`
    {
    unsigned char* ptr = NULL;
    unsigned short StartCRC = b1 + b2*256;
    unsigned long ret = crcbuf(StartCRC, b3, &AuthBlock[b4]);
        ret = (ret & 0x0000ffff) | (crcbuf(StartCRC, b4, &AuthBlock[b3])<<16);
    }

With b1=0xAF b2=0x50

When the function is executed StartCRC = b1 + b2*256; Yields StartCRC = 0x4FAF

I would have expected the results for StartCRC to be 0x50AF.

My question is why does it seem that b2 is reduced by one? Any help would be appreciated. Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems char in your environment is signed and the value 0xAF is sign-extended to value line 0xFFFFFFAF. This will cause that 0xFF is added to tha part of b2 and therefore it looks like b2 is reduced by one.

You should cast b1 to unsigned char to avoid this.

    unsigned short StartCRC = static_cast<unsigned char>(b1) + b2*256;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...