C#函数转换二进制代码



现在,我尝试编写一个C#程序将8个基本二进制转换为文本。

,但我想我对C#的经验不够,无法真正使它起作用。

我认为我想出的代码应该从逻辑上的观点有点做我想要的,但是语法不能正确地做到这一点,因为不知道它。

这是我到目前为止所拥有的:

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

首先,您的代码不会编译。这是错误/错误。

  • 第一个是,在功能的第一行中,您将输入字符串转换为使用String.ToArray()的数组,该字符串返回char[],但您尝试将其分配给变量(代码(键入int[]。您可以通过用char[]var替换int[]来解决此问题。
  • 第二个是在循环(k = 0; k > 7)的第二个内部,您使用Math.Pow()并将其返回值分配给int变量(平方(。但是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);

如果您真的转换为字符串,代码应该看起来像

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

这应该可以解决问题。

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

相关内容

  • 没有找到相关文章

最新更新