Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

c - Print int128 value from struct

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...