Search code examples
c++mathsubtractiontwos-complement

subtracting two values of unknown bitsize


I'm trying to subtract two values from each other using twos compliment. I have a problem with the overflowing bit. Since my container hold an unlimited bit sized integer, I don't know if the top bit of the result is really from the result or just the overflow. How would I get rid of the overflow without using - (I can't just do 1 << bits - 1 since that would involve using the container, which has no working operator- yet)

0b1111011111 - 0b111010000 -> 0b1111011111 + 0b000110000 -> 1000001111

vs (normally)

0b00000101 - 0b000000001 -> 0b00000101 + 0b11111111 -> 0b100000100 -> 0b00000100


Solution

  • If you calculate a - b you must somehow "arrange" the word - as you have to make for the 2 compliment a negation with the bitwidth of m=max(bitwidth(a), bitwidth(b)).

    To get rid of the of overflow you just do mask = negate(1 << m), and apply the mask with bitwise and. (Or you could just check that bit and treat it accordingly).