tags:

views:

86

answers:

3

I have an odd scenario (see this answer for more details), where I need to add two bytes of data together. Obviously this is not normal adding. Here is the scenario:

I am trying to get a coordinate out of a control. When the control is less that 256 in width then the x coordinate takes one byte, otherwise it takes two bites.

So, I now have an instance of that control that is larger than 256 in width. How do I add these two numbers together?

So for example:

  • 2 + 0 is not 2 because the 2 is the high byte (or maybe it is the low byte and it is 2...)

Am I making sense? If so, how can I do this kind of addition in C#?


Update: Sorry for the confusing question. I think I got it figured out. See my answer below.

+2  A: 

You mean something like

256 * high + low

?

Daniel Beck
A: 

Just in case anyone else needs this, I was looking for:

BitConverter.ToInt16

It takes two bytes and converts them to an integer.

Vaccano
And why in the world would you need that at all? That's what I am interested in hearing...
Ed Swangren
@Ed Swangren - good question. It is, unfortunately a long answer. If you read this question you will see what I am trying to do: http://stackoverflow.com/questions/2657388/opennetcf-signature-control-question (More specifically the 3rd comment on that question)
Vaccano
+2  A: 

Approach with multiplying is pretty clear but not common in bitwise word, and your approach with BitConverter takes byte array witch is not convenient in many cases.

The most common (and easy way) to perform this - use bitwise operators:

var r = (high << 8) | low;

And remember about byte ordering because it's not always obvious witch byte is high and witch is low.

Sergey Teplyakov