I was given a task at university to calculate the product of 2 128-bit integer numbers in C language and return the older 64 bits. Feel free to use the code below to print out the lower 128 bits of 128-bit integer product.
UPDATED!!!
My teacher suddenly said he'd meant to print the older 64 bits. I decided to use char * to store all the 128 bits and print out the multiplication result as 128 lower bits. The code below works:
#include <stdio.h>
#include <stdlib.h>
char *moveBit(char *s){ // moves the binary string one bit to the left (like s<<1 operation)
char bit='0';
char temp='0';
for(int i=127;i>=0;i--){
temp = s[i];
s[i]=bit;
bit=temp;
}
return s;
}
char *bitSum(char *a, char *b){ // figures out the sum of two numbers bit by bit
char rem = '0';
char* sum = (char *) malloc(129);
for(int i=127;i>=0;i--){
int s = (a[i]=='1') + (b[i]=='1') + (rem=='1');
if (s==3){
sum[i]='1';
rem='1';
}else if(s==2){
sum[i]='0';
rem='1';
}else{
sum[i] = s? '1':'0';
rem='0';
}
}
return sum;
}
char *mult(char *a, char *b){
char* product = (char *) malloc(129);
for(int i=127;i>=0;i--){
if(b[i]=='1')
product = bitSum(product,a);
a=moveBit(a);
}
return product;
}
int main(){
char *a = (char *) malloc(129);
char *b = (char *) malloc(129);
a="01111111111111111111111111111111101010001101100110100000011111111111111111111111111111111111111111111111111110111111001111111111";
b="01111111111111111111111111111111111111111111110111111001111111111111111111111111111111111111111111111111111111011111100111111111";
printf("%s", mult(a,b));
return 0;
}
long long is not a 128-bit type on any computer I've worked with. See below for references. I'm also assuming that by "last bits" you mean "high bits". This code will work to get unsigned 128-bit arithmetic going on GCC (adjust the type names for your compiler):
#include <stdint.h>
#include <stdio.h>
int main () {
__uint128_t x = 9223372036146775308;
__uint128_t y = 9223372036854709503;
__uint128_t prod = x * y;
uint64_t high = prod >> 64;
printf("%lu\n", high);
}
How long are the types on my machine?
Windows: https://msdn.microsoft.com/en-us/library/94z15h2c.aspx
Linux, Mac OSX, "all other systems": page 13, http://www.x86-64.org/documentation/abi.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With