Search code examples
cbitmapunsigned-integer

Add shifted unsigned bit to unsigned long long (64 bit)


I am trying to perform the following

#include <stdio.h>
#include <stdint.h>
int main()
{

     unsigned long long test = 100; //64 bits
     test = test + (1UL << 33); //assuming 64 bits

     printf("test value %u", test);

     return 0;

}

test prints 100. I was expecting it to add the shifted bit to it.

I can see that there is some issue with its size, as if I, for example add 1UL << 14 test would be equal to 16484.

I am testing it out here: https://onlinegdb.com/r1njSlGjU

How can I go about adding this? I noticed that on my gdb debugger, the code just skips the line that adds does the addition.


Solution

  • The printf function has different formats for different data types. You are using a variable with 'unsigned long long' type but in the printf you are using "%u" which only prints objects of the type "unsigned int". By giving it the wrong 'data type' specifier you cause an undefined behavior. You may refer to the wikipedia: https://en.wikipedia.org/wiki/C_data_types.

    For the right output:

    printf("test value %llu", test);