问题
The C standard and C compilers come with fixed width integer types, such as uint8_t
, int16_t
, etc.
Is there a way of defining a 128-bit integer in C that would be useable in code using the same semantics as the existing fixed-width integers?
回答1:
You'll need something like GMP:
- http://gmplib.org/
You won't get the "exact" semantics.
回答2:
Assuming you're programming a 64-bit machine, you could define a uint128_t
type as a struct
of two uint64_t
s and implement just the arithmetic operators you need by hand. You'd have to manually handle carrying bits from the low 64 bits to the high or vice versa in the case of an operation that overflows in one or the other direction. (For example, add 0xFFFFFFFF to 0x00000001.) That would be much lighter-weight than using an entire library for arbitrary-size bignums like GMP. It'd be a bit tricky to write but by no means impossible--it's pretty much how the built-in BASICs on 8-bit computers back in the day handled math with numbers larger than 255, for example.
来源:https://stackoverflow.com/questions/16491993/is-it-possible-to-create-custom-width-integers-in-c