-2

Hex value of 6378624653 is : 0x17C32168D But this code prints : 0x7C32168D

#include<iostream>

int main()
{
    int x = 6378624653;
    printf("0x%x", x);
}

can anyone explain why this happens ? and what should I do to get the right output?

8
  • 8
    What is the size of an int on your platform?
    – Avi Berger
    Commented Aug 29, 2022 at 17:06
  • 3
    Change to int x{ 6378624653 };. Then you can see the compiler error.
    – Eljay
    Commented Aug 29, 2022 at 17:09
  • 3
    Compile with -Wall Commented Aug 29, 2022 at 17:10
  • 3
    You must have compiler warnings disabled. Turn them on! Your compiler wants to tell you about these problems. Commented Aug 29, 2022 at 17:12
  • 4
    You're using the wrong type for the %x format anyways. %x corresponds to unsigned int not to int. Why do you use printf instead of std::cout anyways? The latter would automatically apply the correct conversion. Furhtermore for printf you should include cstdio, not iostream...
    – fabian
    Commented Aug 29, 2022 at 17:16

1 Answer 1

0

The obtained result means that an object of the type int can not store such a big value as 6378624653.

Try the following test program.

#include <iostream>
#include <limits>

int main() 
{
    std::cout << std::numeric_limits<int>::max() << '\n';
    std::cout << 6378624653 << '\n';
    std::cout << std::numeric_limits<unsigned int>::max() << '\n';
}

and see what the maximum value that can be stored in an object of the type int. In most cases using different compilers you will get the following output

2147483647
6378624653
4294967295

That is even objects of the type unsigned int can not store such value as 6378624653.

You should declare the variable x as having the type unsigned long long int.

Here is a demonstration program.

#include <cstdio>

int main() 
{
    unsigned long long int x = 6378624653;
    printf( "%#llx\n", x );
}

The program output is

0x17c32168d

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.