按位将多个数字打包成一个字节

时间:2017-02-06 15:31:10

标签: .net vb.net bit-shift

我有3个数字,我试图将它们打包成一个字节(0-255)。

Dim num0 As Integer = 6
Dim Num1 As Integer = 17
Dim Num2 As Integer = 30

Dim Packed As Integer = (num0 And &HFFFF) << 1 Or (Num1 And &HFFFF) << 16 Or Num2 And &HFFFF

Dim GotNum0 = (Packed >> 1) And &HFFFF
Dim GotNum1 = (Packed >> 16) And &HFFFF
Dim GotNum2 = Packed And &HFFFF

但输出是10,16,20。

任何人都可以提供帮助。

1 个答案:

答案 0 :(得分:-1)

您不能将这3个数字打包成一个字节,您可以使用整数中的3个字节打包它们。使用掩码选择Packed中的单个字节,以用于您的每个数字(最大值为255)。然后转换Packed

Dim num0 As Integer = 6
Dim Num1 As Integer = 17
Dim Num2 As Integer = 30

Dim Packed As Integer = (num0 And &HFF) Or ((Num1 << 8) And &HFF00) Or ((Num2 << 16) And &HFF0000)

Dim GotNum0 = Packed And &HFF
Dim GotNum1 = (Packed And &HFF00) >> 8
Dim GotNum2 = (Packed And &HFF0000) >> 16