Naruto
9/7/2017 - 12:49 PM

counter128_inc.c

// cc -Wall -o counter128_inc counter128_inc.c
#include <stdio.h>
#include <stdint.h>
#include <memory.h>

/* increment counter (64-bit int) by 1 */
static uint8_t *ctr128_inc(uint8_t counter[16]) {
  uint32_t n=16;
  uint8_t  c;
  do {
    --n;
    c = counter[n];
    ++c;
    counter[n] = c;
    if (c) return counter;
  } while (n);

  return counter;
}

int main() {
  {  
    uint64_t src[2] = {0x0706050403020100L, 0x0f0e0d0c0b0a0908L};
    uint64_t dst[2];
    memcpy(dst, src, sizeof(dst));
    uint8_t *p = (uint8_t*)&dst;

    for(int i=0; i<256; i++) {
      printf("%7d: src: 0x%016llx 0x%016llx dst: 0x%016llx 0x%016llx\n", i, src[1], src[0], dst[1], dst[0]);
      p = ctr128_inc(p);
    }
    printf("%7s: src: 0x%016llx 0x%016llx dst: 0x%016llx 0x%016llx\n", "result", src[1], src[0], dst[1], dst[0]);

  }
  printf("\n");
  {
    uint64_t src[2] = {0x0706050403020100L, 0x0fffffffffffffffL};
    uint64_t dst[2];
    memcpy(dst, src, sizeof(dst));
    uint8_t *p = (uint8_t*)&dst;

    for(int i=0; i<256; i++) {
      printf("%7d: src: 0x%016llx 0x%016llx dst: 0x%016llx 0x%016llx\n", i, src[1], src[0], dst[1], dst[0]);
      p = ctr128_inc(p);
    }
    printf("%7s: src: 0x%016llx 0x%016llx dst: 0x%016llx 0x%016llx\n", "result", src[1], src[0], dst[1], dst[0]);
  }

  return 0;
}