LoginSignup
0
0

More than 1 year has passed since last update.

C言語のビットシフトでエンディアン(バイトオーダー)を処理する

Last updated at Posted at 2022-05-31

(『独習C』第13章の練習問題13.3の大問2)

32ビット整数に対するリトル・ビッグエンディアンの変換をビットシフトで行う関数:

int32_t change_endian(int32_t x)
{
	return (x & 0xff000000) >> 24
		| (x & 0x00ff0000) >> 8
		| (x & 0x0000ff00) << 8
		| (x & 0x000000ff) << 24;
}

の意味について。



まず、32ビットで表すと以下の通り:

0xff000000 = 11111111000000000000000000000000
0x00ff0000 = 00000000111111110000000000000000
0x0000ff00 = 00000000000000001111111100000000
0x000000ff = 00000000000000000000000011111111

ここでは、変換したいやつ(32ビット整数)を

x = A B C D

と書く(ただし、A~Dはそれぞれ8ビット)。

以下のように計算される(=の記号は等号の意味です):

x & 0xff000000 = A 0 0 0 (ここで 0 = 00000000 の8ビット)
(x & 0xff000000) >> 24 = 0 0 0 A ... ①

x & 0x00ff0000 = 0 B 0 0
(x & 0x00ff0000) >> 8 = 0 0 B 0 ... ②

x & 0000ff00 = 0 0 C 0
(x & 0000ff00) << 8 = 0 C 0 0 ... ③

x & 0x000000ff = 0 0 0 D
(x & 0x000000ff) << 24 = D 0 0 0 ... ④

return ① | ② | ③ | ④ = D C B A
0
0
1

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