Search code examples
c#arrayscounterbit

Incrementing bit by bit in byte array (C#)


I have a byte array of two bytes, which I'm using as a counter. I need to increment it bit by bit, as in:

0000 0000 0000 0000
0000 0000 0000 0001
0000 0000 0000 0010
0000 0000 0000 0011
.
.
.
0000 0000 1111 1111
0000 0001 1111 1111
0000 0010 1111 1111
0000 0011 1111 1111

What's the cleanest way of doing this?

EDIT

Sorry for the super stupid question, I was looking at it the wrong way. Should anyone come across the same stupid question in the future: as mentioned in the comments, the easier way to do this is incrementing an Int16.


Solution

  • You can just convert the two bytes for Int16, append the bits you want, and then back to a byte array:

    byte[] byteArray = new byte[2] { 10, 20 }; // your byte array
    Int16 yourNumber = BitConverter.ToInt16(byteArray, 0); // converts your byte array to int16
    yourNumber ++; // increments 1, which will do all the calculations for incrementing the bit(s) and handles overflow...
    byte[] getBytes = BitConverter.GetBytes(yourNumber); // converts the int16 to byte array (I think you should be using Int16, unless you really need to use a byte array)
    

    I'm not sure what exactly you're requesting, if you just want to append a bit to a 2 byte array I think this is the fastest way to do it.