Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to make a program where i can write in a certain number to trigger multiple functions.
But I'm having trouble identifying when a certain number is used. For an example say i have the number "10" i would like to change it to a binary string(00001010) automatically using an algorithm of some-sort. After that i would like to know which bits are on and off so i can call different functions.
Posted
Updated 29-Sep-13 3:14am
v3

1 solution

The term you are looking for is not "byte-form", it's "binary" or possibly "binary string".
Converting it is pretty easy:
C#
int i = 10;
Console.WriteLine(Convert.ToString(i, 2).PadLeft(8, '0'));

But you don't need to convert it to check bits:
C#
    int i = 10;
    for (int j = 7; j >= 0; j--)
        {
        Console.Write(BitValue(i, j));
        }
    Console.WriteLine();
    }
private int BitValue(int i, int bitNo)
    {
    return (i >> bitNo) & 1;
    }
Or even:
C#
    int i = 10;
    Console.WriteLine(Convert.ToString(i, 2).PadLeft(8, '0'));
    for (int j = 7; j >= 0; j--)
        {
        Console.Write(BitValue(i, j) ? '*' : '.');
        }
    Console.WriteLine();
    }
private bool BitValue(int i, int bitNo)
    {
    return (i & (1 << bitNo)) != 0;
    }
 
Share this answer
 
v2
Comments
IAmABadCoder 21-Sep-13 5:23am    
Thanks for that! I never knew it was that easy!
OriginalGriff 21-Sep-13 5:53am    
You're welcome!
Ron Beyer 29-Sep-13 10:36am    
Actually if you are using 8 bit numbers, you can use the Convert.ToByte(string, int) to convert a base-2 string to a byte, like: Convert.ToByte("10", 2) will return a byte value of 2. You can then test for flags with normal binary operations.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900