Click here to Skip to main content
15,886,017 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have a method that will check a character input, and according to the entered character will return an array of bytes consisting of 1's and 0's
(i.e) in case 2 is passed to the method I will get.
b[0] = 0
b[1] = 0
b[2] = 0
b[3] = 0
b[4] = 1
b[5] = 0

The method I tried to implement is returning the ascii equivalent of the 1's and 0's
Is there another way instead of using the below code?

C#
private byte[] determineOutput(char c)
        {
            //byte[] b = new byte[6];
            string s="";
            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            switch (c)
            {
                case '0':
                    s = "000000";
                    break;
                case '1':
                    s= "000001";
                    break;
                case '2':
                    s = "000010";
                    break;
                case 'A':
                    s = "001010";
                    break;
                default:
                    Console.WriteLine("Invalid Characther");
                    break;
            }

            byte[] b = enc.GetBytes(s);

            for (int i = 0; i < b.Length; i++)
            {
                Console.Write(b[i]);
            }
            Console.WriteLine();

            return (b);
        }
Posted

Have you looked at using a BitArray[^] instead?

Alternatively, you could do it like this:
C#
byte[] outp = new byte[5];
for (int i = 0; i < 5; i++)
   {
   outp[i] = (byte) inp & 0x20;
   inp << 1;
   }
return outp;
 
Share this answer
 
This method solved the issue

C#
private byte[] determineOutput(char c)
        {
            byte[] b = new byte[6];
            //byte b = 11;

            switch (c)
            {
                case '0':
                    b = new byte[6] { 0, 0, 0, 0, 0, 0 };
                    break;
                case '1':
                    b = new byte[6] { 0, 0, 0, 0, 0, 1 };
                    break;
                case '2':
                    b = new byte[6] { 0, 0, 0, 0, 1, 0 };
                    break;
                case 'A':
                    b = new byte[6] { 0, 0, 1, 0, 1, 0 };
                    break;
                default:
                    Console.WriteLine("Invalid Characther");
                    break;
            }


            for (int i = 0; i < b.Length; i++)
            {
                Console.Write(b[i]);
            }
            Console.WriteLine();

            return (b);
        }
 
Share this answer
 

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