如何连接2个字节?

时间:2009-12-20 10:16:09

标签: c# byte

我有2个字节:

byte b1 = 0x5a;  
byte b2 = 0x25;

如何获得0x5a25

6 个答案:

答案 0 :(得分:35)

可以使用按位运算符'<<'来完成和'|'

public int Combine(byte b1, byte b2)
{
    int combined = b1 << 8 | b2;
    return combined;
}

用法示例:

[Test]
public void Test()
{
    byte b1 = 0x5a;
    byte b2 = 0x25;
    var combine = Combine(b1, b2);
    Assert.That(combine, Is.EqualTo(0x5a25));
}

答案 1 :(得分:17)

使用位运算符: (b1 << 8) | b2或同样有效(b1 << 8) + b2

答案 2 :(得分:5)

一个更明确的解决方案(也可能更容易理解并扩展到字节到整数,即:)

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Byte2Short {
  [FieldOffset(0)]
  public byte lowerByte;
  [FieldOffset(1)]
  public byte higherByte;
  [FieldOffset(0)]
  public short Short;
}

用法:

var result = (new Byte2Short(){lowerByte = b1, higherByte = b2}).Short;

这让编译器可以完成所有的bit-fiddling,因为Byte2Short是一个struct而不是一个类,所以new甚至不会分配一个新的堆对象;)

答案 3 :(得分:1)

byte b1 = 0x5a;
byte b2 = 0x25;

Int16 x=0;

x= b1;
x= x << 8;
x +=b2;

答案 4 :(得分:0)

最简单的是

b1*256 + b2

答案 5 :(得分:0)

这个问题有点含糊不清。

如果是字节数组,您可以简单地: byte [] myarray = new byte [2]; myarray [0] = b1; myarray [1] = b2; 你可以序列化byearray ......

或者如果你正在尝试将这些16位填充到int或类似的东西中,你可以在c#中学习你的按位运算符... http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts

做类似的事情:

byte b1 = 0x5a; byte b2 = 0x25; int foo = ((int) b1 << 8) + (int) b2;

现在你的int foo = 0x00005a25。

相关问题