I am testing CTR mode on STM32 board. I want to know how the auto increment of counter happens and what is the method to follow if I have to increment the counter manually.

enter image description here


1 Answer 1


Basically there are two ways:

  1. decode the counter to be a big number in some kind of library, increase that number, then encode it back as unsigned, statically sized, big endian value, making sure you left pad with zero valued bytes when necessary;

  2. increase the value of the right-most byte (highest index) as unsigned number, if the resulting value is zero then increase the value of the byte before that, up to the leftmost byte if required (i.e. use a bit of awkward carry-bit detection).

Probably 2 is easier and less error prone; you'd just need a single loop construct, one expression to increase the byte value and an if statement to detect the carry by comparing to 00 afterwards.

  • $\begingroup$ Of course, if you're thinking about it, it doesn't matter that you look at the bytes as unsigned numbers when you compare to zero. Signed numbers however fail if you compare <= instead of ==. $\endgroup$
    – Maarten Bodewes
    May 12, 2016 at 7:09
  • $\begingroup$ uint8_t ctr[8] = ...; unsigned i, t = 0; for (i = 0; i < 8; i++) { t += ctr[i]; ctr[i] = t & 0xff; t >>= 8; } if (t) { overflow(); } $\endgroup$ Aug 1, 2017 at 19:44
  • $\begingroup$ @SqueamishOssifrage: I believe you mean to initialize t to 1 :-) $\endgroup$
    – poncho
    Aug 1, 2017 at 22:08
  • 1
    $\begingroup$ @poncho: Well, if you really wanted a correct algorithm for some reason, I guess...! $\endgroup$ Aug 2, 2017 at 13:19

Your Answer

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

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