Decimal to hex for int64 in c
Why this code do开发者_如何学Pythones not work ?
#include <iostream>
#include <cstdio>
int main() {
printf("%X", 1327644190303473294);
}
I am getting o/p 5f264e8e
but expected o/p is 126cbd5b5f264e8e
as given by below php script
<?php
echo dechex(1327644190303473294);
?>
format '%X' expects type 'unsigned int', but argument 2 has type 'long int'
#include <stdio.h>
int main(void) {
printf("%lX",1327644190303473294);
return 0;
}
outputs
126CBD5B5F264E8E
The portable way to do this is to
#include <inttypes.h>
And to do:
#include <stdio.h>
#include <inttypes.h> // for PRIX64 macro (and INT64_C macro from stdint.h)
int main(void)
{
printf("The value is %"PRIX64"\n", INT64_C(1327644190303473294));
return 0;
}
%X
is for int
, which is usually 32-bit. The required incantation for a 64-bit number is platform-dependent. On the Mac, it's %qX
.
You need to use a different format specifier to indicate that your integer is 64 bits wide. As it stands, your code interprets the input as a 32 bit integer.
In MSVC this would be %I64x
, on some platforms it would be %lx
and there are indeed other specifiers.
In summary, you need to choose a specifier appropriate for your particular toolset.
for uint64_t, you can try as follow:
uint64_t val = 1327644190303473294;
printf("val: 0x%llx\n", val);
精彩评论