tags:

views:

327

answers:

6

I have 2 bytes:

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

How do I get 0x5a25 ?

A: 

The simplest would be

b1*256 + b2
Pavel Radzivilovsky
(b1 << 8) + b2 will do the job faster.
futureelite7
@futureelite7, that's unlikely to be the case with modern compilers - in any case, you should have used (b1<<8)|b2 :-)
paxdiablo
@futureelite7: I note that `b1*256+b2` has one fewer character than `(b1<<8)+b2` so actually `b1*256+b2` is faster. :-)
Jason
+12  A: 

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

Nick Fortescue
"+" is not usually considered a bit(-wise) operator
dionadar
+1  A: 
byte b1 = 0x5a;
byte b2 = 0x25;

Int16 x=0;

x= b1;
x= x << 8;
x +=b2;
Hellfrost
+22  A: 

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));
}
Elisha
I'm pretty certain you didn't need to wrap that in a function :-) But you're right, so +1.
paxdiablo
Beware of http://en.wikipedia.org/wiki/Endianness. It really matters what the bytes will be used for. Alhough most c# work is done on the Intel platform, the bytes may be send out as a part of network protocol where endiannes matters.
danatel
oh the OR is nice :-) but it is still short... +1 for the OR :)
Hellfrost
A: 
Dave Quick
+3  A: 

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

dionadar
union is evil...
Hellfrost
maybe - but if you want to express that something can be understood more than one way on a bit-wise level it is the tool of choice. Personally I prefer the shift+or method, but it becomes quite cumbersome when your target is i.e. a uint64, while the union still remains very readable in that case.
dionadar