从 int 获取单个字节

use*_*928 2 c# binary

我得到了一个整数。例如 5630(十进制)。二进制数为:

00000000 00000000 00010101 11111110

我想以十进制(00010101)获取第二个字节。我如何得到它?

D S*_*ley 5

您可以使用BitConverter.GetBytes()

int intValue = 5630;
byte[] intBytes = BitConverter.GetBytes(intValue);
byte result = intBytes[1];  // second least-significant byte
Run Code Online (Sandbox Code Playgroud)

或者只是向右移位 8 位并转换为一个字节(截断左边的位):

((byte)(intValue >> 8))
Run Code Online (Sandbox Code Playgroud)