简体   繁体   中英

Question regarding hexadecimal multiplication in C using datatype int64_t

When I try to carry out hex multiplication of 16 bits by 16bits using the datatype int64_t, the result displayed is restricted to 32 bits, and a 33rd bit, if present is never displayed, although I am defining the operands as well as result to be 64 bits in length.

Here is the simple code I am using:

#include<stdio.h>  
#include <stdint.h>  

int main()  
{  
   int64_t a, b, r;  
   a = 0xabcd;  
   b = 0xdbca;  
   r = a * b * 3;  
   printf("%x", r);  
   return 0;  
} 

Result printed out is : ba7fcc46

Expected Result is : 1ba7fcc46

Kindly help me out here.

The format specifier for int64_t depends on platform ( %I64x on Windows, %llx on any other platform, YMMV). So there is a macro you can use that looks ugly but will work on any system:

#include <inttypes.h>
...
printf("%" PRIx64 "\n", r);

If you don't mind your code not working on Windows, you can just use %llx .


(Edited; the name of the macro was wrong)

A popular solution is to use %llx for your printf format. ll means long long (64-bit long on virtually all systems), although this is not portable.

The portable (however, less legible) solution, is to use @anatolyg's answer, reprinted here:

#include <inttypes.h>
// ...
printf("%" PRIx64 "\n", r);

what we do is this

#if __WORDSIZE == 64
printf("%lx\n", r);
#else
printf("%llx\n", r);
#endif

This keeps the type correct for both 64 bit and 32 bit machines. BTW this is for gcc/g++. Not sure if it's portable

Actually, there are only a few ways for a conforming program to specifically print an int64_t , and they all look about like this:

#include <stdio.h>
#include <inttypes.h>

void f(int64_t x) {
  printf("Value %30" PRId64 "\n", x);
}

int main(void) {
  f((int64_t)1000000000 * 1000000000);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM