Scranton
Scranton

Reputation: 13

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.

Upvotes: 1

Views: 4196

Answers (4)

DigitalRoss
DigitalRoss

Reputation: 146221

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

Upvotes: 0

Jonathan
Jonathan

Reputation: 13624

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

Upvotes: 2

anatolyg
anatolyg

Reputation: 28300

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)

Upvotes: 4

DavidMFrey
DavidMFrey

Reputation: 1668

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

Upvotes: 0

Related Questions