addition of "binary" numbers
What is the re开发者_StackOverflowsult of adding the binary numbers 01000001 and 11111111 on an 8 bit machine?
If we are supposed to interpret this with the rules of C (it is tagged as such), for the signed case there are three interpretations of these numbers possible, corresponding to the three sign representations that are allowed in C.
For the unsigned case the standard requires that unsigned arithmetic wraps silently. All computation is done modulo 256 in that case.
Integer overflow.
If the numbers are unsigned (i.e. modular), 0100000 (with modular 8-bit math, addition of 11111111 is equal to subtraction of 1).
If both values are unsigned, then the result is 320 in decimal. Both operands are promoted to int before the addition, and int is required by the standard to have at least 16 bits, even on an 8 bit machine. The question doesn't make any restrictions for the result.
Unless you want the "wrong result fast", the answer is 320.
Correctly adding two numbers (in whatever representation) anywhere (including 8-bit machines) results in a unique number that can be represented in a multitude of different ways.
320 can be represented as 320 (usual decimal (base-10) representation) or 101000000 (binary representation) or 253413120100 (factoradic), ...
I think you just add the numbers, then cut the overflowing bits (from the left)
if it's only 8 bit, the maximum you can have is 255 (1111 1111) if the value is unsigned and 127 if it is signed (-128 being the lowest). Therefore, doing this addition will cause overflow, which goes back to 0 and then keeps counting. Think of it as your car miles meter: if there can only be, say, 8 digits on the counter, and your counter is at 99 999 999 miles, if you add one more, the counter will go back to 0.
- If these are signed integers, they represent 65 and
-128-1. Adding them will give-6364. - If these are unsigned integers, they represent 65 and 255. Since the sum can not be represented in 8 bits, the result will be 64 and the overflow bit will be set.
精彩评论