Last active
June 6, 2022 14:30
-
-
Save guitarrapc/55272a9595783337a0131a99c36dea4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void Main() | |
| { | |
| // 符号なし (unsigned) の 0xFF = 255 | |
| byte u = 0xFF; | |
| // 符号付き (signed) の 0xFF = -1 | |
| sbyte s = (sbyte)u; | |
| // 符号なしを右シフトすると、左端には 0 が入る。 | |
| // 11111111 FF | |
| // 01111111 7F | |
| // 00111111 3F | |
| // 00011111 1F | |
| // 00001111 F | |
| // 00000111 7 | |
| // 00000011 3 | |
| // 00000001 1 | |
| for (int i = 0; i < 8; i++) | |
| { | |
| Console.WriteLine($"{Convert.ToString(u, 2).PadLeft(8, '0')} {u:X}"); | |
| u >>= 1; | |
| } | |
| // 符号なしを右シフトすると、左端のビットが残る。 | |
| // 元が FF だとずっと FF。 | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| // 11111111 FF | |
| for (int i = 0; i < 8; i++) | |
| { | |
| Console.WriteLine($"{Convert.ToString((byte)s, 2).PadLeft(8, '0')} {s:X}"); | |
| s >>= 1; | |
| } | |
| // LogicalRightShift を呼んでいるので、符号なし右シフトになる。 | |
| // 11111111 FF | |
| // 01111111 7F | |
| // 00111111 3F | |
| // 00011111 1F | |
| // 00001111 F | |
| // 00000111 7 | |
| // 00000011 3 | |
| // 00000001 1 | |
| for (int i = 0; i < 8; i++) | |
| { | |
| Console.WriteLine($"{Convert.ToString((byte)s, 2).PadLeft(8, '0')} {s:X}"); | |
| s = LogicalRightShift(s, 1); | |
| } | |
| // 右シフトの符号のあり/なしを切り替えたい場合、キャストを挟む。 | |
| static sbyte LogicalRightShift(sbyte s, int bits) | |
| => (sbyte)((byte)s >> bits); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment