ライブラリの使用を推奨するのは、このような場合です。
GMPを使用すると、次の変換を行うことができます (gmp.c):
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(int argc, char *argv)
{
// From string
char *s ="199999999999999999999999999999999999999";
mpz_t i;
// To big number, using GMP
// 10 here means base 10.
mpz_init_set_str(i, s, 10);
// Just to test if s is 128 bits long
printf("%s can be represented with %d digits in base 2\n",s, mpz_sizeinbase(i, 2));
// Then you can print it in hex
gmp_printf("%#32ZX\n", i);
// Or convert it back to int[4]
unsigned int a[4];
mpz_export(&a, NULL, 1, 4, 0, 0, i);
for(int x=0;x<4;x++)
printf("%X\n", a[x]);
mpz_clear(i);
return 0;
}
出力:
199999999999999999999999999999999999999 can be represented with 128 digits in base 2
0X96769950B50D88F41314447FFFFFFFFF
96769950
B50D88F4
1314447F
FFFFFFFF
このコードを 32 ビット Linux システムでテストしました。異なるプラットフォームでは異なる int サイズとエンディアンに注意してください。結果をビッグ エンディアンで表示したい場合は、mz_export を次のように変更します。
mpz_export(&a, NULL, 1, 4, 1, 0, i);
サンプルをコンパイルするには、gmp をインストールし、gcc コマンド ライン パラメータに -lgmp -std=c99 を追加することを忘れないでください。
Ubuntu では、次の方法で gmp をインストールできます。
sudo apt-get install libgmp-dev
サンプル gmp.c をコンパイルします。
gcc gmp.c -o gmp -lgmp -std=c99
このコードは、コンバージョンの良いスタートとなります。大きな数値がゼロで始まる場合に備えて、 i を固定の 128 ビット数値に初期化することもできます (GMP の init 関数を使用)。