mastofact
mastofact

Reputation: 550

C# integer masking into byte array

I'm confused as to why this isn't working, can someone please provide some insight?

I have a function who is taking in an integer value, but would like to store the upper two bits of the hex value into a byte array element.

Let's say if Distance is (24,135)10 or (5E47)16

public ConfigureReportOptionsMessageData(int Distance, int DistanceCheckTime)
    {
        ...
        this._data = new byte[9];
        this._data[0] = (byte)(Distance & 0x00FF); // shows 47
        this._data[1] = (byte)(Distance & 0xFF00); // shows 00
        this._data[2] = (byte)(DistanceCheckTime & 0xFF);
        ...
    }

Upvotes: 2

Views: 1873

Answers (3)

codekaizen
codekaizen

Reputation: 27419

The reason you get 0 for _data[1] is that the upper 3 bytes are lost when you cast to byte.

Your intermediate result looks like this:

Distance && 0xff00 = 0x00005e00;

When this is converted to a byte, you only retain the low order byte:

(byte)0x00005e00 = 0x00;

You need to shift by 8 bits:

0x00005e00 >> 8 = 0x0000005e;

before you cast to byte and assign to _data[1]

Upvotes: 1

Vlad
Vlad

Reputation: 35584

this._data[1] = (byte)(Distance >> 8);

?

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564333

This seems like you should be using BitConverter.GetBytes - it will provide a much simpler option.

Upvotes: 2

Related Questions