How do I concatenate 2 bytes?

落爺英雄遲暮 提交于 2019-12-21 04:15:12

问题


I have 2 bytes:

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

How do I get 0x5a25 ?


回答1:


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));
}



回答2:


Using bit operators: (b1 << 8) | b2 or just as effective (b1 << 8) + b2




回答3:


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 ;)




回答4:


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

Int16 x=0;

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



回答5:


The simplest would be

b1*256 + b2



回答6:


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...

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

do something similar to:

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

now your int foo = 0x00005a25.



来源:https://stackoverflow.com/questions/1935449/how-do-i-concatenate-2-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!