-2

What is the best way to increment/decrement a byte in c++ while taking into consideration the overflow and underflow? For example, I have:

char c = random byte;
c += 0xB;

In case c <= 0xF4, this will work well, but any value above that would cause an overflow. Likewise, if it was c -= 0xB; and c < 0xB, an underflow would occur.

Let's say c = 0xFF, after the addition, will it be 0xA? Likewise with the underflow, if c = 0, will the result be 0xF5?

Also, for some odd, reasons, when I increase specific numbers, weird results occur. For example, if I increase 0x0 by 0xA, using the code:

c = (c + 0xA) & 0xFF;

the result is: 0x0D 0x0A and not just 0x0A... just as shown in the following image: Increment Issue

While all the rest of the bytes increase correctly.

11
  • I can't spot a single increment or decrement operation. Feb 9, 2015 at 16:51
  • I'm not sure I used the correct word to describe the operation since I'm not a native speaker, but this is what I meant with increment: c = (c + 0xA). I also just edited the code since I forgot to change variables used in the code appropriately. @πάνταῥεῖ Feb 9, 2015 at 16:52
  • Are you trying to use this for encryption? Maybe you're wanting to use exclusive or instead. Feb 9, 2015 at 16:54
  • 2
    @BraveHeart That's called addition (and the opposite is subtraction). Increment/decrement is usually used when a value is added/subtracted 1. Feb 9, 2015 at 16:55
  • 3
    At least as far as the 0A it seems very clear that you're on a Windows system, and that your file I/O is helpfully translating a \n to \r\n (native end of line indicator) for you.
    – Mark B
    Feb 9, 2015 at 16:57

1 Answer 1

1

I can at least explain your results with 0x0 by 0xA: On Windows, a newline in text files is typically represented as \r\n rather than \n and the file I/O functions will helpfully make this translation for you. In this case you don't desire the conversion though so you could open the file in binary mode which will inhibit the automatic conversion.

As for handling overflow, if you are able to use unsigned char instead of char, it's guaranteed to have well-defined modulo arithmetic for overflow and underflow.

If you need to handle signed over/under flow you're going to have to carefully code up all the logic you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.