将字符串数组转换为二进制字符串

时间:2020-07-09 01:26:06

标签: c#

我有一个包含数字元素的字符串数组:

string[] numbers = {"2","3","10","9","4"};

我想将每个字符串转换为等效的16位二进制文​​件并进行连接,这样生成的字符串必须如下所示:

00000000000000100000000000000011000000000000101000000000000010010000000000000100

我是否必须将字符串数组转换为int数组并应用/ 2函数,还是有其他有效的方法来实现?另外,如何获得16位结果?

3 个答案:

答案 0 :(得分:0)

string result = string.Join("", numbers.Select(n => Convert.ToString(Int16.Parse(n), 2).PadLeft(16, '0')));

答案 1 :(得分:0)

using System;
using System.Text;

namespace Proggram
{
    internal class Program
    {


        internal static int Main(string[] args)
        {
            var sb = new StringBuilder();
            string[] numbers = { "2", "3", "10", "9", "4" };
            foreach (var number in numbers)
            {
                sb.Append(NumbertoStrToBinaryStr(number));
            }

            Console.WriteLine(sb.ToString());
            return 0;
        }


        private static string NumbertoStrToBinaryStr(string numberstr)
        {
            var result = new StringBuilder();
            if (!uint.TryParse(numberstr, out var n)) return result.ToString();

            const int start =  32 - 1;
            for (var mask = 1u << start; mask != 0; mask >>= 1)
            {
                var set = (mask & n) == mask;
                result.Append( set ? '1' : '0');
            }

            return result.ToString();
        }
    }
}

答案 2 :(得分:0)

您可以使用for循环访问每个元素,例如此代码...

string binary_number ="";
string[] numbers = { "2", "3", "10", "9", "4" };
for (int i = 0;i < numbers.Length;i++) {
  binary_number += Convert.ToString(Int16.Parse(numbers[i]), 2).PadLeft(16, '0')));
}