1

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.

Community
  • 1
  • 1
Vaccano
  • 78,325
  • 149
  • 468
  • 850

3 Answers3

2

You mean something like

256 * high + low

?

Daniel Beck
  • 6,363
  • 3
  • 35
  • 42
2

Approach with multiplying is pretty clear but not common in bitwise word, and your approach with BitConverter takes byte array which 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 which byte is high and which is low.

Falcz
  • 5
  • 3
Sergey Teplyakov
  • 11,477
  • 34
  • 49
1

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

BitConverter.ToInt16

It takes two bytes and converts them to an integer.

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 1
    And why in the world would you need that at all? That's what I am interested in hearing... – Ed S. Oct 04 '10 at 21:23
  • @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 Oct 04 '10 at 21:27