Signed & unsigned integer multiplication

☆樱花仙子☆ 提交于 2019-11-30 22:26:12
Benjamin Leinweber

This post Talks about what happens when multiplying signed and unsigned integers. Short answer is, as long as they are the same rank (size), a signed is implicitly typecast to unsigned.

As long as you understand the typecasting rules (of whatever language you are programming in), or use explicit typecasting, and you also understand the implications of typecasting from signed to unsigned (a negative number will produce what may appear as gibberish when typecasted to a signed value), then there should be no issue mixing signed and unsigned types.

I had a similar problem. It caused an access violation crash in x64 version. The code iterates through a buffer of image scan lines. Getting the next scan line pointer goes as:

unsigned char* pImg = ...
int stride = -3324;
unsigned int iRow = 1; // 2, 3, 4, ...
unsigned char* pNextLine = pImg + stride * iRow

Negative stride means iterating from bottom towards top scan line. The product stride * iRow i.e. signed * unsigned is typecasted to unsigned __int64 with value 4294963972 which pushes the pNextLine out of program's memory.

The same happens with the x32 program version, but there is no crash. Maybe because the x32 pNextLine pointer just wraps around (but stays within the program's memory).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!