1

My goal is to be able to convert a string into binary code that is still a string. I am able to turn the string into byte[] but not back to a string without decoding it.

0

3 Answers 3

2

You can use the Convert method for that:

byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
Sign up to request clarification or add additional context in comments.

2 Comments

I guess that's exactly what he wants. 'to a string of binary'
Yes I missed the part where he wanted "still as a string"
1

If you can encode/decode a byte, e.g.

private static String ToBinary(Byte value) {
  StringBuilder Sb = new StringBuilder(8);

  Sb.Length = 8;

  for (int i = 0; i < 8; ++i) {
    Sb[7 - i] = (Char) ('0' + value % 2);

    value /= 2;
  }

  return Sb.ToString();
}

private static Byte FromBinary(String value) {
  int result = 0;

  for (int i = 0; i < value.Length; ++i)
    result = result * 2 + value[i] - '0';

  return (Byte) result;
}

You can easily encode/decode a whole string:

  // Encoding... 
  String source = "abc";

  // 011000010110001001100011
  String result = String.Join("", UTF8Encoding.UTF8.GetBytes(source).Select(x => ToBinary(x)));

  ... 

  // Decoding...
  List<Byte> codes = new List<Byte>();

  for (int i = 0; i < result.Length; i += 8) 
    codes.Add(FromBinary(result.Substring(i, 8)));

  // abc
  String sourceBack = UTF8Encoding.UTF8.GetString(codes.ToArray());

Comments

0

use

string str = "Welcome"; 
byte []arr = System.Text.Encoding.ASCII.GetBytes(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.