user2069776
user2069776

Reputation: 1

Form a binary number from drop down lists

So, I have 8 drop down lists that are populated with the values 0 and 1. With the selected values from those 8 drop down lists, I want to put them together to make a binary number. From there I'd convert the binary number to a decimal(the decimal output would be displayed in a textbox, so the decimal number would change everytime a different number in any of the drop down lists is changed).

But I'm unsure of how to get all 8 of the selected values combined to make an 8-bit binary number so I can convert it once I get that number. Any suggestions on how I should start this?

Upvotes: 0

Views: 235

Answers (2)

Srikant Krishna
Srikant Krishna

Reputation: 881

For each "bit", shift it.

So, if the highest bit is 1, do 1 << 8

Then, do a bitwise or (|) to create the final binary number.

int i = 1 << 8;
i |= (0 << 7);
i |= (1 << 6);

The values I'm using above (1, 0, 1 ..) should be from your drop down box.

If you put the dropdown boxes into a list or array, you can very concisely write this whole code as:

int x = 0;
for (int i=dropdowns.Length - 1; i >= 0; i--) {
x |= int.Parse(dropdowns[i].Text) << i;    
}

This also allows you to use a variable number of dropdowns.

Upvotes: 0

leppie
leppie

Reputation: 117280

The really bad (but easy) way:

Convert.ToInt32(dd7.Text + dd6.Text + dd5.Text + dd4.Text + 
                dd3.Text + dd2.Text + dd1.Text + dd0.Text, 2)

Upvotes: 1

Related Questions