Search code examples
cpointersuint16

Pointer assignment - uint16_t


I was looking at a problem from cs61c (ucb). I have the following method:

void lfsr_calculate(uint16_t *reg) {                                      
  uint16_t result = compute_bit_val(*reg);                              
  printf("reg value: %d", *reg);                                        
  printf("bit val result: %d", result);                                 
  printf("bit val result shifted: %d", result << 16);                   
  *reg >>= 1;                                                           
  printf("bit val result shifted plus zero: %d", *reg + (result << 16));
  *reg = (uint16_t) *reg + (result << 16);                              
  printf("new reg: %d", *reg);                                          
}

If *reg is 1, my method compute_bit_val returns 1. The print output is

1 

1

65536

65536

**0**

?!?!?! I am pulling out my hair, I don't know why the last part is zero, for some reason the assignment is not working. I tried this with and without casting, and it gives the same result.


Solution

  • In the last step, you assign 65536 to *reg which is uint16_t. However uint16_t can only store values from 0 to 65535, so it gets adjusted via modular arithmetic to have value 0. (aka. wraps around).

    You may be overlooking that integer arithmetic is always performed in at least int precision; narrower types are immediately promoted to int before computing the result of any arithmetic operator.