-1

Right now I try to write a C# Program to translate 8 Base Binary into Text.

But I guess I am not experienced enough with C# to truly make it Work.

I think the code I come up with, should, from a logical Point-of-View somewhat do what I want, but the Syntax isn't properly doing it, since don´t know it better.

This is what I have so far:

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");
    }
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • What isn't working? Describe the problem in more detail rather than just saying "Syntax isn´t properly doing it". – Matt Hogan-Jones May 30 '17 at 12:37
  • 1
    You can try this [answer](https://stackoverflow.com/questions/6006425/binary-to-corresponding-ascii-string-conversion) – Vijay May 30 '17 at 12:47
  • 1
    `convertBin` should be static, as i'm assuming this is a console application. Also your program won't output anything. – DrNachtschatten May 30 '17 at 12:51
  • Looks like we have enough solutions now; welrocken's looks very well thought through, and reasonably efficient as well. I could add my own solution in F# but I guess it would be off-topic… :) – dumetrulo May 31 '17 at 09:36

3 Answers3

2

First of all, your code won't compile. Here are the errors/mistakes.

  • The first one is, at the first line of your function, you are converting the input string to an array using String.ToArray(), which returns a char[] but your try to assign it to a variable (code) typed int[]. You can solve this by replacing the int[] with either char[] or var.
  • The second one is, inside the second for loop (k = 0; k > 7), you use Math.Pow() and assign it's return value to an int variable (Squared). But Math.Pow returns double. You can solve this by casting the return value of Math.Pow to int. Like; int Squared = (int)Math.Pow(2, k);
  • The last thing is not easily solvable like the first two because, your code is not exactly correct. You are trying to return something called translated, which is a variable of type StringBuilder. But your function is defined to return an int.

Now these were compile errors. There are a bunch of logical and decision errors/mistakes. Your algorithm also isn't very correct.

Here is a sample code you can use/examine. I'd like to help you further, why your code was incorrect, what was your design mistakes etc. if you want to.

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

This code passes these assertions.

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);
welrocken
  • 266
  • 1
  • 9
0

If you are really converting to a string the code should look like this

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

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

this should do the trick.

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;
}
DrNachtschatten
  • 392
  • 5
  • 11