0

I have this int128 that is a tuple of 2 64-bit integers:

struct int128 {

    uint64_t    left;
    int64_t     right;
};

I know how to make basic arithmetic like multiply, addition and subtraction, but I don't know how to print the current signed value in C.

Can someone show me please how to do that?

1 Answers1

0

Assuming you have the following function:

int64_t divideRem(struct int128 *number, int64_t divisor);

That divides number / divisor, setting the division result on number, and returns the remainder of the division.

You could use a recursive implementation:

printInt128rec(struct int128 *number) {
  int64_t rem;
  rem = divideRem(number, 10);
  if( cmpInt128(number, 0) != 0 ) { /* compares number with 0 */
    printInt128rec(number);
  }
  printf("%d", rem);
}

Your main print function should copy the number to avoid modifications, and check for negatives:

printInt128(struct int128 *number) {
  struct int128 copy = *number;
  if( cmpInt128(&copy, 0) < 0 ) {  /* number is negative */
    printf("-");
    becomePositive(&copy); /* copy = abs (number ) */
  }
  printInt128rec(&copy);
}

Now you may call printInt128 to print your numbers. Notice that I used several other functions that operates between an int128 integer and an int64. If you know how to make 128 bits arithmetics these should be easier to implement.

Will
  • 891
  • 1
  • 7
  • 11
  • Thank you ! - i did the same before i saw your post. Happy that your solution confirm that i did the right thing :) - once again thank you! – sakdkjkj jjsdjds Mar 30 '21 at 07:37