How to "Add" two bytes together

15,476

Solution 1

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.

Solution 2

You mean something like

256 * high + low

?

Solution 3

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

BitConverter.ToInt16

It takes two bytes and converts them to an integer.

Share:
15,476
Ali Mst
Author by

Ali Mst

I am an IT Software Architect from Salt Lake City, Utah.

Updated on September 03, 2022

Comments

  • Ali Mst
    Ali Mst over 1 year

    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.

    • Thomas Levesque
      Thomas Levesque over 13 years
      "Am I making sense?": no, absolutely not... why are you using bytes in the first place, rather than a more adequate type like int ?
    • Ed S.
      Ed S. over 13 years
      ...huh? why are you worrying about bytes at all? Width is an integer.
    • Hamish Grubijan
      Hamish Grubijan over 13 years
      I bet you 1,000,000.00 that you can solve it with a bool variable.
    • Ali Mst
      Ali Mst over 13 years
      @Hamish Grubijan - maybe, but I would need about 1,000,000 bools.
    • Daniel Mošmondor
      Daniel Mošmondor over 13 years
      One byte, two bites, 8 is a whole meal :-D
  • Ed S.
    Ed S. over 13 years
    And why in the world would you need that at all? That's what I am interested in hearing...
  • Ali Mst
    Ali Mst over 13 years
    @Ed Swangren - good question. It is, unfortunately a long answer. If you read this question you will see what I am trying to do: stackoverflow.com/questions/2657388/… (More specifically the 3rd comment on that question)