1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

符号拡張(C言語)

Last updated at Posted at 2022-06-03

符号付き16ビット整数と、符号なし16ビット整数についての符号拡張を考える(『独習C』第2章)。

#include <stdio.h>
#include <stdint.h>

int main()
{
	int32_t i32 = -10;
	int16_t i16 = i32;
	uint16_t u16 = i32;

	i32 = i16;
	printf("%i\n", i32);  // => -10

	i32 = u16;
	printf("%i\n", i32);  // => 65526
}

まず、符号付き32ビット整数i32を-10=1111 1111 1111 1111 1111 1111 1111 0110で初期化する。

その後、この32ビット整数を16ビットのi16u16に代入している。

すると、i16u16の両方には、上位32ビットが切り捨てられた1111 1111 1111 0110が代入される。

i32 = i16;
printf("%i\n", i32);  // => -10

符号付き16ビットのi16(= 1111 1111 1111 0110)が、32ビットへ符号拡張される。

i16は”符号付き”なので、拡張する際は値1で拡張される。つまりi321111 1111 1111 1111 1111 1111 1111 0110が代入れる。

それで、printfしてやると-10という結果になる。

i32 = u16;
printf("%i\n", i32)  // => 65526

符号なしu16(= 1111 1111 1111 0110)が32ビットへ符号拡張される。

”符号なし”なので、拡張する際は値0で拡張される。つまりi320000 0000 0000 0000 111 1111 1111 0110が代入される。

それでprintfしてやると65526という結果になる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?