Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...