rakeeee
rakeeee

Reputation: 1073

Unsigned and signed division in C

In my program two variables are declared as signed long (let say X and Y on 32 bit machine) and these divided one by other(X/Y).

The final value is assigned to a unsigned long variable(Let say Z). I am not sure whether this is right or wrong assignment. I am just debugging a code that was written by some one. I guess this may lead to overflow or undefined state.

What happens in below four scenarios,

Z =+X/+Y  
Z =+X/-Y  
Z =-X/+Y  
Z =-X/-Y

I know that %u for unsigned and %d for integer. My question is regarding what value would be stored in Z in the above four scenarios.

Any help would be greatly appreciated.

Upvotes: 2

Views: 14699

Answers (3)

neciu
neciu

Reputation: 4495

You'll get garbage if result of division is negative.

For example:

unsigned z;
int a = 10;
int b = -2;
z = a/b;

then z == 4294967291.

Upvotes: 1

m0skit0
m0skit0

Reputation: 25874

Z would store the value of the integer division, but as Z is unsigned, all values will be positive, and thus the sign bit will not be processed as such, but as part of the number, and also there will be no two's complement conversion. For example, if unsigned int is 32-bit wide:

X = 1, Y = 1 -> Z = 1
X = -1, Y = 1 -> Z = 4294967295 = 0xFFFFFFFF (this would be -1 -two's complement- if Z was signed)

Upvotes: 0

glglgl
glglgl

Reputation: 91139

If your variables are signed, all is fine. Perhaps there is a (unwanted?) conversion afterwards if you gert a negative division result.

Working with expressions containing unsigned values is more painful, e.g.

(1U-2)/10

gives unexpected results.

Upvotes: 1

Related Questions