开关盒(返回字节[]) [英] Switch Case (return byte[])

查看:94
本文介绍了开关盒(返回字节[])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检查字符输入的方法,根据输入的字符将返回由1和0组成的字节数组.
(即)如果将2传递给我将得到的方法.
b [0] = 0
b [1] = 0
b [2] = 0
b [3] = 0
b [4] = 1
b [5] = 0

我尝试实现的方法返回的是等价于1''s和0''s的ascii
有没有其他方法可以代替下面的代码?

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?

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);
        }

推荐答案

您是否使用过
Have you looked at using a BitArray[^] instead?

Alternatively, you could do it like this:
byte[] outp = new byte[5];
for (int i = 0; i < 5; i++)
   {
   outp[i] = (byte) inp & 0x20;
   inp << 1;
   }
return outp;


此方法解决了该问题

This method solved the issue

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);
        }


这篇关于开关盒(返回字节[])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆