LoginSignup
2
1

More than 3 years have passed since last update.

[C言語アルゴリズム]エンディアンネス

Last updated at Posted at 2020-05-06

C言語でエンディアン確認アルゴリズムを実装した

学習にあたって使用した環境

  • ideone.com (https://ideone.com/) ※オンライン上でプログラミング学習ができるサイト

参考資料

C言語による最新アルゴリズム辞典 (奥村晴彦著/1991年初版 技術評論社:16ページ)

エンディアンの概要

上位バイトと下位バイトの順序を俗にエンディアンという。
メモリの若番地が下位バイトなのがリトルエンディアン、その逆がビッグエンディアン。

endian.png
引用元:http://www.ertl.jp/~takayuki/readings/info/no05.html

ソースコード

endian.c
/* endianness エンディアンネス */
/* int型のエンディアンネスを調べる */

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i = 1;

    if(*((char *)&i))
    {
        printf("little-endian\n");
    }
    // iをchar*にキャストして、int-1サイズ分ポインタの参照先をズラした値が≠0の場合真
    else if(*((char *)&i + (sizeof(int) - 1)))
    {
        printf("big-endian\n");
    }
    else
    {
        printf("不明\n");
    }

    return EXIT_SUCCESS;
}

実行結果

リトルエンディアンであると結果が出た。

result.txt(任意)
Success #stdin #stdout 0s 4380KB

little-endian
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1