C# 如何连接 2 个字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1935449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I concatenate 2 bytes?
提问by jawal
I have 2 bytes:
我有 2 个字节:
byte b1 = 0x5a;
byte b2 = 0x25;
How do I get 0x5a25
?
我如何获得0x5a25
?
回答by Pavel Radzivilovsky
The simplest would be
最简单的是
b1*256 + b2
回答by Nick Fortescue
Using bit operators:
(b1 << 8) | b2
or just as effective (b1 << 8) + b2
使用位运算符:
(b1 << 8) | b2
或同样有效(b1 << 8) + b2
回答by AK_
byte b1 = 0x5a;
byte b2 = 0x25;
Int16 x=0;
x= b1;
x= x << 8;
x +=b2;
回答by Elisha
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));
}
回答by Dave Quick
The question is a little ambiguous.
这个问题有点模棱两可。
If a byte array you could simply: byte[] myarray = new byte[2]; myarray[0] = b1; myarray[1] = b2; and you could serialize the byearray...
如果是字节数组,您可以简单地: byte[] myarray = new byte[2]; myarray[0] = b1; myarray[1] = b2; 你可以序列化 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;
byte b1 = 0x5a; byte b2 = 0x25; int foo = ((int) b1 << 8) + (int) b2;
now your int foo = 0x00005a25.
现在你的 int foo = 0x00005a25。
回答by gha.st
A more explicit solution (also one that might be easier to understand and extend to byte to int i.e.):
一个更明确的解决方案(也是一个可能更容易理解并扩展到字节到整数的解决方案,即):
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 ;)
这让编译器可以做所有的位操作,因为 Byte2Short 是一个结构体,而不是一个类,new 甚至不分配一个新的堆对象;)