[英]How do I concatenate 2 bytes?
I have 2 bytes: 我有2个字节:
byte b1 = 0x5a;
byte b2 = 0x25;
How do I get 0x5a25
? 我怎么得到0x5a25
?
It can be done using bitwise operators '<<' and '|' 它可以使用按位运算符'<<'和'|'来完成
public int Combine(byte b1, byte b2)
{
int combined = b1 << 8 | b2;
return combined;
}
Usage example: 用法示例:
[Test]
public void Test()
{
byte b1 = 0x5a;
byte b2 = 0x25;
var combine = Combine(b1, b2);
Assert.That(combine, Is.EqualTo(0x5a25));
}
Using bit operators: (b1 << 8) | b2
使用位运算符: (b1 << 8) | b2
(b1 << 8) | b2
or just as effective (b1 << 8) + b2
(b1 << 8) | b2
或同样有效(b1 << 8) + b2
A more explicit solution (also one that might be easier to understand and extend to byte to int ie): 一个更明确的解决方案(也可能更容易理解并扩展到byte到int ie):
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Byte2Short {
[FieldOffset(0)]
public byte lowerByte;
[FieldOffset(1)]
public byte higherByte;
[FieldOffset(0)]
public short Short;
}
Usage: 用法:
var result = (new Byte2Short(){lowerByte = b1, higherByte = b2}).Short;
This lets the compiler do all the bit-fiddling and since Byte2Short is a struct, not a class, the new does not even allocate a new heap object ;) 这让编译器可以完成所有的bit-fiddling,因为Byte2Short是一个struct而不是一个类,所以new甚至不会分配一个新的堆对象;)
byte b1 = 0x5a;
byte b2 = 0x25;
Int16 x=0;
x= b1;
x= x << 8;
x +=b2;
最简单的是
b1*256 + b2
The question is a little ambiguous. 问题有点含糊不清。
If a byte array you could simply: byte[] myarray = new byte[2]; 如果一个字节数组你可以简单地:byte [] myarray = new byte [2]; myarray[0] = b1; myarray [0] = b1; myarray[1] = b2; myarray [1] = b2; and you could serialize the byearray... 你可以序列化byearray ...
or if you're attempting to do something like stuffing these 16 bits into a int or similar you could learn your bitwise operators in c#... http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts 或者如果你试图将这些16位填充到int或类似的东西中,你可以在c#中学习你的按位运算符... http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
do something similar to: 做类似的事情:
byte b1 = 0x5a; byte b2 = 0x25; int foo = ((int) b1 << 8) + (int) b2;
now your int foo = 0x00005a25. 现在你的int foo = 0x00005a25。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.