user1231497
user1231497

Reputation: 13

Amend 10 bits of 2 bytes

In C#, how would I go about setting 2 bytes where the first 10 bits represent one decimal value and the next 6 represent a different decimal value?

So if the first value was '8' (first 10 bits) and the second '2' (remaining 6 bits), I need to end up with '0000001000 000010' inside a byte array.

Thanks! Ad

Upvotes: 1

Views: 343

Answers (4)

Douglas
Douglas

Reputation: 54887

int val1 = 8;
int val2 = 2;

// First byte contains all but the 2 least significant bits from the first value.
byte byte1 = (byte)(val1 >> 2);

// Second byte contains the 2 least significant bits from the first value,
// shifted 6 bits left to become the 2 most significant bits of the byte,
// followed by the (at most 6) bits of the second value.
byte byte2 = (byte)((val1 & 4) << 6 | val2);

byte[] bytes = new byte[] { byte1, byte2 };

// Just for verification.
string s =
    Convert.ToString(byte1, 2).PadLeft(8, '0') + " " +
    Convert.ToString(byte2, 2).PadLeft(8, '0');

Upvotes: 1

Justin
Justin

Reputation: 6711

UInt16 val1 = 8;
UInt16 val2 = 2;
UInt16 combined = (UInt16)((val1 << 6) | val2);

If you need it in a byte array, you can pass the result to the BitConverter.GetBytes method.

byte[] array = BitConverter.GetBytes(combined);

Upvotes: 4

itsme86
itsme86

Reputation: 19496

ushort value = (8 << 6) | 2;
byte[] bytes = BitConverter.GetBytes(value);

Upvotes: 0

Bruno Brant
Bruno Brant

Reputation: 8564

Not accounting for any kind of overflow:

private static byte[] amend(int a, int b)
{
    // Combine the datum into a 16 bits integer
    var c = (ushort) ((a << 6) | (b));
    // Fragment the Int to bytes
    var ret = new byte[2];
    ret[0] = (byte) (c >> 8);
    ret[1] = (byte) (c);

    return ret;
}

Upvotes: 0

Related Questions