Search code examples
c#binaryinteger-arithmetic

C# Building a Integer value with Binary operations from "Bits"


I have a array of bytes that are actually binary values like this

byte[] buf = new byte[] { 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

The binary representation is 1111 1110 (0xFF = 0, 0xF0= 1).

The value of the integer or byte that needs to be built from this is 0xFE (254).

I have thought about converting buf to a string of 1s and 0s and then back to an integer, but there must exist more elegant ways to accomplish this with binary operations.

The Pascal code that is known to do this perfectly is (using a string):

  if NumberOfBytes > 0  then begin    // there was a response
     for c := Length(Str) downto 1 do begin
        Ch := Str[c];
        if (ord(ch) AND 2) = 0 then begin
           Sin := Sin + '0';
        end else begin
           Sin := Sin + '1';
        end;
        INC(Teller);
        if (Teller mod 8) = 0 then begin
            N := BinaryStrToByte(Sin);
            Edit2.Text := Edit2.Text + ByteHex(N) + ' ' ;
            Sin := '';
        end;
     end;

Also C code that doesn't seem to port to C# because of some differences in behavior:

for(bytes = 0; bytes < len; bytes++)
 {
   newByte=0;
   for(bits=0; bits<8; bits++)
   {
     newByte >>= 1;
    if(inBuf[0]==0xff) 
    {
      newByte |= 0x80;
    }
   }
   pBuf[bytes]=newByte;
 }

I want to effectively loop through my original array and then put a real binary 0 or 1 into an int or byte, depending if I have the 0xF0 or 0xFF value in at the current position.


Solution

  • This might do the trick:

    public static void Main()
    {
        byte[] buf = new byte[] { 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
        byte result = 0;
        foreach(var b in buf.Reverse())
        {
            result <<= 1;
            if(b == 0xFF) result |= 1;
        }
        Console.WriteLine(result);
    }