Hadi
Hadi

Reputation: 995

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.

Upvotes: 0

Views: 137

Answers (2)

Sean Tashlik
Sean Tashlik

Reputation: 176

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);

Upvotes: 4

Aplet123
Aplet123

Reputation: 35530

It actually is adding the value, you just don't realize it, since you're printing it out with %u. This converts the value to an unsigned int, which means that it's just 100. If you print with %llu for unsigned long long, it'll print out correctly.

Upvotes: 1

Related Questions