string values to byte array without converting

25,171

Solution 1

Are you saying you have something like this:

string s = "48656c6c6f2c20776f726c6421";

and you want these values as a byte array? Then:

public IEnumerable<byte> GetBytesFromByteString(string s) {
    for (int index = 0; index < s.Length; index += 2) {
        yield return Convert.ToByte(s.Substring(index, 2), 16);
    }
}

Usage:

string s = "48656c6c6f2c20776f726c6421";
var bytes = GetBytesFromByteString(s).ToArray();

Note that the output of

Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(bytes));

is

Hello, world!

You obviously need to make the above method a lot safer.

Solution 2

Encoding has the reverse method:

byte[] data  = System.Text.Encoding.UTF8.GetBytes(originalString);

string result = System.Text.Encoding.UTF8.GetString(data);

Debug.Assert(result == originalString);

But what you mean 'without converting' is unclear.

Solution 3

One way to do it would be to write:

string s = new string(bytes.Select(x => (char)c).ToArray());

That will give you a string that has one character for every single byte in the array.

Another way is to use an 8-bit character encoding. For example:

var MyEncoding = Encoding.GetEncoding("windows-1252");
string s = MyEncoding.GetString(bytes);

I'm think that Windows-1252 defines all 256 characters, although I'm not certain. If it doesn't, you're going to end up with converted characters. You should be able to find an 8-bit encoding that will do this without any conversion. But you're probably better off using the byte-to-character loop above.

Share:
25,171
Gisli
Author by

Gisli

Starting my third year in CS at Reykjavík University. Currently working at Miracle

Updated on January 18, 2022

Comments

  • Gisli
    Gisli over 2 years

    I'm trying to put the values of a string into a byte array with out changing the characters. This is because the string is in fact a byte representation of the data.

    The goal is to move the input string into a byte array and then convert the byte array using:

    string result = System.Text.Encoding.UTF8.GetString(data);
    

    I hope someone can help me although I know it´s not a very good description.

    EDIT: And maybe I should explain that what I´m working on is a simple windows form with a textbox where users can copy the encoded data into it and then click preview to see the decoded data.

    EDIT: A little more code: (inputText is a textbox)

        private void button1_Click(object sender, EventArgs e)
        {
            string inputString = this.inputText.Text;
            byte[] input = new byte[inputString.Length];
            for (int i = 0; i < inputString.Length; i++)
            {
                input[i] = inputString[i];
            }
            string output = base64Decode(input);
            this.inputText.Text = "";
            this.inputText.Text = output;
        }
    

    This is a part of a windows form and it includes a rich text box. This code doesn´t work because it won´t let me convert type char to byte. But if I change the line to :

        private void button1_Click(object sender, EventArgs e)
        {
            string inputString = this.inputText.Text;
            byte[] input = new byte[inputString.Length];
            for (int i = 0; i < inputString.Length; i++)
            {
                input[i] = (byte)inputString[i];
            }
            string output = base64Decode(input);
            this.inputText.Text = "";
            this.inputText.Text = output;
        }
    

    It encodes the value and I don´t want that. I hope this explains a little bit better what I´m trying to do.

    EDIT: The base64Decode function:

        public string base64Decode(byte[] data)
        {
            try
            {
                string result = System.Text.Encoding.UTF8.GetString(data);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }
    

    The string is not encoded using base64 just to be clear. This is just bad naming on my behalf.

    Note this is just one line of input.

    I've got it. The problem was I was always trying to decode the wrong format. I feel very stupid because when I posted the example input I saw this had to be hex and it was so from then on it was easy. I used this site for reference: http://msdn.microsoft.com/en-us/library/bb311038.aspx

    My code:

         public string[] getHexValues(string s)
         {
            int j = 0;
            string[] hex = new String[s.Length/2];
            for (int i = 0; i < s.Length-2; i += 2)
            {
                string temp = s.Substring(i, 2);
                this.inputText.Text = temp;
                if (temp.Equals("0x")) ;
                else
                {
                    hex[j] = temp;
                    j++;
                }
            }
            return hex;
        }
    
        public string convertFromHex(string[] hex)
        {
            string result = null;
            for (int i = 0; i < hex.Length; i++)
            {
                int value = Convert.ToInt32(hex[i], 16);
                result += Char.ConvertFromUtf32(value);
            }
            return result;
        }
    

    I feel quite dumb right now but thanks to everyone who helped, especially @Jon Skeet.

  • Gisli
    Gisli almost 13 years
    thanks for answering. This is what I mean but when I try to use the ToArray() functions I get an error saying there is no definition for ToArray().
  • jason
    jason almost 13 years
    @Gisli: Add a reference to System.Core and a using System.Linq; directive at the top of your code.
  • Gisli
    Gisli almost 13 years
    Thanks. Now I get an error message: Could not find any recognizable digits. I´ll let you know if I figure it out.
  • derek
    derek over 9 years
    I need to store some data in my app.config file that i dont want to be in plain text, same concept. this helped thanks. -1 to whoever down voted the OP, i hate SO snobs who think that everyone on here is a professional developer. we all have to start somewhere. Great answer