C#函数转换二进制代码

时间:2017-05-30 12:34:58

标签: c# binary translate

现在我尝试编写一个C#程序,将8 Base Binary翻译成Text。

但我想我对C#的经验不足以让它真正发挥作用。

我认为我提出的代码应该从逻辑的Poi​​nt-of-View中做出我想要的,但语法没有正确地执行它,因为不要更好地了解它。

这是我到目前为止所做的:

using System;
using System.Linq;
using System.Text;

class binaryTranslate
{
    public int convertBin(string CodeInput)
    {
        int [] code = CodeInput.ToArray();
        int CodeCount = code.ToString().Length;
        int EightBaseSegAmount = CodeCount / 8;
        int ByteCapacity = 8;
        StringBuilder translated = new StringBuilder();

        for (var i = 1; i < EightBaseSegAmount + 1; i++)
        {
            StringBuilder Byte = new StringBuilder(ByteCapacity);
            int ByteStart = (i * 8) - 8;
            int ByteEnd = (i * 8) - 1;
            int ByteIncrement = 1;

                for (var j = ByteStart ; j < ByteEnd + 1; j++)
                {
                    Byte.Append(code[j]);
                }

            for (var k = 0; k > 7; k++)
            {
                int BitValue = 128;


                if (Byte[k] == 1)
                {
                    if (k > 0)
                    {
                        int Squared = Math.Pow(2, k);
                        ByteIncrement += BitValue / Squared;
                    }
                    else
                    {
                        ByteIncrement += BitValue; 
                    }
                }

            }
            char toSymbol = Convert.ToChar(ByteIncrement);
            translated.Append(toSymbol);
        }

        return translated;
    }

    public static int Main()
    {
        convertBin("010010000110000101101100011011000110111100100001");
    }
}

3 个答案:

答案 0 :(得分:2)

首先,您的代码无法编译。这是错误/错误。

  • 第一个是,在函数的第一行,您使用String.ToArray()将输入字符串转换为数组,返回char[],但您尝试将其分配给变量(代码)输入int[]。您可以将int[]替换为char[]var来解决此问题。
  • 第二个是,在第二个for循环(k = 0; k > 7)内,您使用Math.Pow()并将其返回值分配给int变量(Squared)。但Math.Pow返回加倍。您可以通过将Math.Pow的返回值转换为int来解决此问题。喜欢; int Squared = (int)Math.Pow(2, k);
  • 最后一件事不像前两个那样容易解决,因为你的代码并不完全正确。您正在尝试返回名为translated的内容,该内容是StringBuilder类型的变量。但是您的函数被定义为返回int

现在这些都是编译错误。存在许多逻辑和决策错误/错误。你的算法也不是很正确。

以下是您可以使用/检查的示例代码。我想进一步帮助您,为什么您的代码不正确,您的设计错误是什么等等。

class binaryTranslate
{
    public enum IncompleteSegmentBehavior
    {
        Skip = 0,
        ZerosToStart = 1,
        ZerosToEnd = 2
    }

    private byte ConvertBinstrToByte(string sequence)
    {
        if (string.IsNullOrEmpty(sequence))
            return 0; // Throw?

        if (sequence.Length != sizeof(byte) * 8)
            return 0; // Throw?

        const char zero = '0';
        const char one = '1';

        byte value = 0;
        for (int i = 0; i < sequence.Length; i++)
        {
            if (sequence[i] != zero && sequence[i] != one)
                return 0; // Throw

            value |= (byte)((sequence[i] - zero) << (7 - i));
        }

        return value;
    }

    private string HandleIncompleteSegment(string segment, int segmentSize, IncompleteSegmentBehavior behavior)
    {
        string result = null;

        var zeroAppender = new StringBuilder();
        for (int i = 0; i < segmentSize - segment.Length; i++)
            zeroAppender.Append('0');

        var zeros = zeroAppender.ToString();

        switch (behavior)
        {
            case IncompleteSegmentBehavior.Skip:
                break;
            case IncompleteSegmentBehavior.ZerosToStart:
                result = zeros + result;
                break;
            case IncompleteSegmentBehavior.ZerosToEnd:
                result = result + zeros;
                break;
            default:
                break;
        }

        return result;
    }

    public byte[] ConvertBinstrToBytes(string binarySequence, IncompleteSegmentBehavior behavior = IncompleteSegmentBehavior.Skip)
    {
        var segmentSize = sizeof(byte) * 8;

        var sequenceLength = binarySequence.Length;

        var numberOfBytes = (int)Math.Ceiling((double)sequenceLength / segmentSize);
        var bytes = new byte[numberOfBytes];

        for (int i = 0; i < numberOfBytes; i++)
        {
            var charactersLeft = sequenceLength - i * segmentSize;
            var segmentLength = (charactersLeft < segmentSize ? charactersLeft : segmentSize);
            var segment = binarySequence.Substring(i * segmentSize, segmentLength);

            if (charactersLeft < segmentSize)
            {
                segment = HandleIncompleteSegment(segment, segmentSize, behavior);
                if (segment == null)
                    continue;
            }

            bytes[i] = ConvertBinstrToByte(segment);
        }

        return bytes;
    }
}

此代码传递了这些断言。

var bytes = new binaryTranslate()
    .ConvertBinstrToBytes("00000000");

Assert.Equal(bytes.Length, 1);
Assert.Equal(bytes[0], 0b00000000);

bytes = new binaryTranslate()
    .ConvertBinstrToBytes("10000000");

Assert.Equal(bytes.Length, 1);
Assert.Equal(bytes[0], 0b10000000);

bytes = new binaryTranslate()
    .ConvertBinstrToBytes("11111111");

Assert.Equal(bytes.Length, 1);
Assert.Equal(bytes[0], 0b11111111);

bytes = new binaryTranslate()
    .ConvertBinstrToBytes("00000001");

Assert.Equal(bytes.Length, 1);
Assert.Equal(bytes[0], 0b00000001);

bytes = new binaryTranslate()
    .ConvertBinstrToBytes("1100110000110011");

Assert.Equal(bytes.Length, 2);
Assert.Equal(bytes[0], 0b11001100);
Assert.Equal(bytes[1], 0b00110011);

答案 1 :(得分:0)

如果您真的转换为字符串,则代码应如下所示

namespace binaryTranslate
{
    class Program
    {
        static void Main(string[] args)
        {

            //convertBin("01001000 01100001 01101100 01101100 01101111 00100001");
            string results = BinaryTranslate.convertBin(new byte[] { 0x44, 0x61, 0x6c, 0x6c, 0x6f, 0x21 });
        }
    }
   public  class BinaryTranslate
    {
        public static string convertBin(byte[] CodeInput)
        {
            return string.Join("", CodeInput.Select(x => x.ToString("X2")));

        }
    }
}

答案 2 :(得分:0)

这应该可以解决问题。

public static string FromBinary(string binary)
{
    int WordLength = 8;

    binary = binary.Replace(' ', '');
    while(binary.Length % WordLength != 0)
        binary += "0";

    string output = String.Empty;
    string word = String.Empty;
    int offset = 0;

    while(offset < binary.Length)
    {
        int tmp = 0;
        word = binary.Substring(offset, 8);
        for(int i=0; i<(WordLength - 1); i++)
            if(word[i] == '1')
                tmp += (int) Math.Pow(2, i);

        output += Convert.ToChar(tmp);
        offset += WordLength;
    }

    return output;
}
相关问题