2

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);
        ...
    }
3
  • 4
    You forgot the bitshifting... Commented Nov 4, 2010 at 0:07
  • 2
    BTW - what are you doing with the other 2 bytes in Distance? Commented Nov 4, 2010 at 0:13
  • @Reed Copsey: Nothing, there was a maximum set. If it was meters, the limit was 30,000. Commented Nov 4, 2010 at 0:18

3 Answers 3

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

?

Sign up to request clarification or add additional context in comments.

1 Comment

(byte)(Distance >> 8), not (byte)(Distance >> 16)
2

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

4 Comments

I think he heeds a 9 byte array. BitConverter.GetBytes would then need an Array.Copy or Buffer.Copy.
@codekaizen: Yeah, but I'd still say it's more maintainable, since it's obvious what's being done.
I somewhat disagree. After writing and maintaining a binary protocol handler, using BitConverter is less easy to maintain. Surprised me, too.
@codekaizen: Yeah - depends on how your data stream is coming into the routine. In this case, converting from int to byte - I'd prefer to maintain somebody's code using BitConverter than bitshifting - especially given that it's going into a single large array. Intent is easier to follow.
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.