2

I am currently writing a program in C. I have a variable i declared in my program. I have initialized it as such:

 unsigned char i = 0x00;

Next, I have a while loop, and inside that while loop, I'm increasing the unsigned char by 16 and displaying it to seven digits (such as 0000080). Well, This runs perfectly fine for the first 16 values, but whenever the unsigned char gets to 00000f0 and gets incremented again, it goes back to 0000000. Why is this and how can I alter my code to fix this? Thanks in advance.

1 Answers1

7

An unsigned char, assuming 8 bit to a byte, has a maximum value of 255 (0xff). Any arithmetic operation that exceeds that is truncated modulo 256.

If you want to support larger values, use unsigned int instead.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you! I didn't realize chars were only 8 bits. I'll accept as soon as I can. – Matthew Vanlandingham Feb 07 '18 at 19:47
  • 3
    @MatthewVanlandingham Detail: `char` are not "only 8 bits". `char` are usually "8 bits". On select platforms, they are wider. – chux - Reinstate Monica Feb 07 '18 at 19:50
  • Thanks for clarifying. On my particular machine, it is 8 bits :D – Matthew Vanlandingham Feb 07 '18 at 19:52
  • By the C standard `char` is *at least* 8 bits, and on many (perhaps most) platforms it is exactly 8 bits. On some current (embedded) DSP platforms, `char` is 16 bits. Back In The Day, on some Cray supercomputers, `char`, `short`, `int`, and `long` (this was in the days before `long long`) were *all* 64 bits, and thus `sizeof(long) == 1`. – mlp Feb 07 '18 at 20:18