Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string values to byte array without converting

Tags:

c#

.net

casting

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.

like image 979
Gisli Avatar asked Jun 06 '11 15:06

Gisli


People also ask

How do you convert a string to a byte array?

Using String.getBytes () The String class provides three overloaded getBytes methods to encode a String into a byte array: String inputString = "Hello World!" ; byte [] byteArrray = inputString.getBytes (); The above method is platform-dependent, as it uses the platform's default charset.

Can we use any charset for decoding a byte array?

However, we can't just use any charset for decoding a byte array. In particular, we should use the charset that encoded the String into the byte array. We can also convert a byte array to a String in many ways.

How to print the byte array without B in Python?

In this example, I have taken a string as b’ python guides’ which includes a byte array, then the string is decoded to print the byte array without b. To decode the string, I have used newstring = string.decode (). To print the string without b I have used print (newstring).

How to encode a string to a byte array in Java?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes. We refer to the above process as encoding.


2 Answers

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.

like image 62
jason Avatar answered Oct 27 '22 14:10

jason


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.

like image 41
Henk Holterman Avatar answered Oct 27 '22 14:10

Henk Holterman