Solved

C# - Convert byte[] to bit mask

Posted on 2010-08-26
3
2,533 Views
Last Modified: 2013-12-17
Experts,

I'm writing an web app which contains a large series of Checkboxes on a page.  Once the user selects which options he/she wants I am creating a byte array like this:

//Just using 4 for simplicity:
byte[] options = new byte[4]
options[0] = Convert.ToByte(cbOption1.Checked);
options[1] = Convert.ToByte(cbOption2.Checked);
options[2] = Convert.ToByte(cbOption3.Checked);
options[3] = Convert.ToByte(cbOption4.Checked);

So saying that options 1 and 2 where checked I will end up with a byte[] array looking like this: 1100, which is expected.  I want to convert this to an integer (i.e. a bitmask) which 1100 should equal 12.

So I googled "C# byte[] to int" and most everything comes up using the BitConverter class, but I'm getting some weird values.

One example shows the checking for LittleEndian processor architecture. So:

if(BitConverter.IsLittleEndian)
      Array.Reverse(options);

int optionBitMask = BitConverter.ToInt32(options, 0);

And optionBitMask shows up as 16,842,752.

If I remove the reversing for LittleEndian and just use:

int optionBitMask = BitConverter.ToInt32(options, 0);

Then optionBitMask shows up as 257.

I'm not sure what I'm doing wrong.  How do I get an int value of 12 from a byte[] containing 1100 ?
0
Comment
Question by:P1ST0LPETE
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 2

Assisted Solution

by:eoindevery
eoindevery earned 50 total points
ID: 33534762
You should use BitArrays instead of ByteArrays


> How do I get an int value of 12 from a byte[] containing 1100 ?

using System.Collections;

---------------------------------------

BitArray ba = new BitArray(4);
            ba.Set(3, true);
            ba.Set(2, true);
            ba.Set(1, false);
            ba.Set(0, false);
            //ba= 1100

            int[] array = new int[1];
            ba.CopyTo(array, 0);
            Console.WriteLine(array[0]);

-> will give you 12
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 450 total points
ID: 33534835
You're storing "bit" values in an entire byte for each position. You would need to treat each position as a bit rather than a byte. You can do so by working with the value of each byte and using a combination of shift and bitwise-or operations:
byte[] data = new byte[] { 1, 1, 0, 0 };
int result = 0;

for (int i = data.Length - 1; i >= 0; i--)
{
    result |= (data[i] << (data.Length - (i + 1)));
}

Console.WriteLine(result);

Open in new window

0
 
LVL 10

Author Comment

by:P1ST0LPETE
ID: 33535410
Thanks guys, was working on the following when I read your post:

private int BytesToInt(byte[] bytes)
{
        int result = 0;

        for (int i = 0; i < bytes.Length; i++)
        {
                result += bytes[i] << i;
        }

        return result;
}

So I was close, but obviously missing some crucial steps that kaufmed cleared up.  Also, had forgotten about the BitArray as there is no "bit" data type - well there's bool, but that's not exactly a bit. You know what i mean.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
asp web application 3 43
ASP.NET Calendar Control 5 29
TFS 2015 Access denied. 1 30
What is newest platform to convert a massive Windows Forms program to? 7 52
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question