Data type conversion

A forum devoted to the discussion of all topics having to do with scripting and other advanced programming using iX Developer.
Post Reply
Sunshine12
Posts: 12
Joined: Fri Sep 14, 2012 6:27 am

Data type conversion

Post by Sunshine12 »

Hi i am haveing a bit of trouble converting a byte to a string.
I have a byte loaded into a string variable and i need to convert it into ASCII
i have tried a number of approaches e.g. System.text.ASCIIEncoding.ASCII.GetString(string)
but still no luck.
Could someone please help me out. Thanks

Sunshine12
Posts: 12
Joined: Fri Sep 14, 2012 6:27 am

Re: Data type conversion

Post by Sunshine12 »

HI there sorry after further investigation.
what i need to do is convert ASCII code back into its decimal or HEX form.

User avatar
Edmund
Posts: 92
Joined: Thu Nov 29, 2012 2:27 pm

Re: Data type conversion

Post by Edmund »

Maybe this can help you.

Here you convert a string to the ASCII hex values.

Code: Select all


void Button1_Click(System.Object sender, System.EventArgs e)
{   
    AnalogNumeric1.Text = ASCIIStringToHex("Beijer");
}

public string ASCIIStringToHex(string ascii)
{
    string hex = ""; 
    char[] chars = ascii.ToCharArray();
            
    foreach (char c in chars)
        hex += ((Int16)c).ToString("x");
    
    return hex;
}
Code above will set the text in AnalogNumeric1 to 4265696a6572 (Beijer).

And the other direction

Code: Select all

void Button1_Click(System.Object sender, System.EventArgs e)
{
    byte[] myByteArray = StringHexToByteArray("4265696a6572");
    AnalogNumeric1.Text = System.Text.Encoding.ASCII.GetString(myByteArray);
}

public byte[] StringHexToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
       bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes; 
}
Edmund Andersson

AITECH AB

Part of Beijer Integrator Group

Sunshine12
Posts: 12
Joined: Fri Sep 14, 2012 6:27 am

Re: Data type conversion

Post by Sunshine12 »

Thanks i managed to get it working late last night

User avatar
Edmund
Posts: 92
Joined: Thu Nov 29, 2012 2:27 pm

Re: Data type conversion

Post by Edmund »

Great :)
Edmund Andersson

AITECH AB

Part of Beijer Integrator Group

Post Reply