Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two signed or unsigned integers

It has been a long time since I last programmed at the bits and bytes level and wanted to confirm something I seem to remember from those days:

Say I have two integers of equal length (1, 2, 4, 8 bytes; it doesn't matter), and I add them up: does the bit-by-bit result of the sum differ if they are signed or unsigned. In other words: regardless of whether they are signed or unsigned integers, will the bits end up being the same?

My intuition and my frail memory tell me they will, but I just wanted to confirm. Thanks.

like image 700
Eduardo Avatar asked Feb 19 '13 16:02

Eduardo


1 Answers

Assuming the implementation uses 2's complement as representation of signed integers, then the results will be the same. In other representations, they won't.

EDIT

As pointed out in comments, overflow in signed addition is undefined behaviour, which means nothing can be said about the results in such case.

like image 67
Angew is no longer proud of SO Avatar answered Oct 21 '22 00:10

Angew is no longer proud of SO