Eskalior
Eskalior

Reputation: 252

Simple Calculation gives wrong result

I have this simple piece of code:

Logger::LogFloat("width", m_BMPLoader->GetWidth());
Logger::LogFloat("height", m_BMPLoader->GetHeight());
Logger::LogFloat("width / 4", (m_BMPLoader->GetWidth() / 4));
Logger::LogFloat("height / 4", (m_BMPLoader->GetHeight() /4));
Logger::LogFloat("-width / 4", -(m_BMPLoader->GetWidth() / 4));
Logger::LogFloat("-height / 4", -(m_BMPLoader->GetHeight() / 4));
Logger::LogFloat("-width /4 * Plane", -(m_BMPLoader->GetWidth() / 4) * PLANE_WIDTH);
Logger::LogFloat("-height / 4 * Plane", -(m_BMPLoader->GetHeight() / 4) * PLANE_WIDTH);

Giving this result:

width: 128
height: 128
width / 4: 32
height / 4: 32
-width / 4: 4.29497e+009          //should be -32
-height / 4: 4.29497e+009         //should be -32
-width /4 * Plane: 4.29497e+009   //should be -160
-height / 4 * Plane: 4.29497e+009 //should be -160

EDIT: Solved. I used unsigned int and signed it.

Upvotes: 1

Views: 128

Answers (2)

unsigned arithmetic operates modulo 2^n for some value n. -(m_BMPLoader->GetWidth() / 4) is actually being calculated as 2^32 - 32, which is approximately 4294967264 - hence your results.

Upvotes: 1

aschepler
aschepler

Reputation: 72271

If x is an unsigned int, then -x is also an unsigned int, with the value pow(2,n)-x, where n is the number of bits in an unsigned int.

You will need a cast somewhere to a signed type (integral or floating type).

Upvotes: 1

Related Questions