Is it possible to create custom-width integers in C?

戏子无情 提交于 2020-01-04 18:30:11

问题


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_ts 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!