【发布时间】:2009-12-20 10:16:08
【问题描述】:
我有 2 个字节:
byte b1 = 0x5a;
byte b2 = 0x25;
我如何获得0x5a25?
【问题讨论】:
-
"add" 不能很好地描述这个操作。连接?
我有 2 个字节:
byte b1 = 0x5a;
byte b2 = 0x25;
我如何获得0x5a25?
【问题讨论】:
可以使用按位运算符'
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));
}
【讨论】:
使用位运算符:
(b1 << 8) | b2 或同样有效的(b1 << 8) + b2
【讨论】:
一种更明确的解决方案(也是一种可能更容易理解和扩展到字节到 int 的解决方案):
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;
这让编译器可以做所有的位摆弄,因为 Byte2Short 是一个结构,而不是一个类,new 甚至不分配一个新的堆对象;)
【讨论】:
BitConverter.ToUInt16(new[] { b2, b1, }, 0)。
byte b1 = 0x5a;
byte b2 = 0x25;
Int16 x=0;
x= b1;
x= x << 8;
x +=b2;
【讨论】:
最简单的应该是
b1*256 + b2
【讨论】:
b1*256+b2 比(b1<<8)+b2 少一个字符,所以实际上b1*256+b2 更快。 :-)
这个问题有点模棱两可。
如果是字节数组,您可以简单地: 字节[] myarray = 新字节[2]; 我的数组 [0] = b1; 我的数组 [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。
【讨论】: