Welcome Guest ( Login | Register )



All times are UTC - 7 hours [ DST ]



Post new topic Reply to topic  [ 5 posts ] 
Author Message
 Post subject: Data type conversion
PostPosted: Thu Mar 14, 2013 9:24 am 

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

Offline
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


 Profile  
 
 Post subject: Re: Data type conversion
PostPosted: Thu Mar 14, 2013 3:44 pm 

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

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


 Profile  
 
 Post subject: Re: Data type conversion
PostPosted: Thu Mar 14, 2013 4:39 pm 
User avatar

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

Offline
Maybe this can help you.

Here you convert a string to the ASCII hex values.

Code:

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:
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


 Profile  
 
 Post subject: Re: Data type conversion
PostPosted: Fri Mar 15, 2013 2:48 am 

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

Offline
Thanks i managed to get it working late last night


 Profile  
 
 Post subject: Re: Data type conversion
PostPosted: Fri Mar 15, 2013 3:15 am 
User avatar

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

Offline
Great :)

_________________
Edmund Andersson

AITECH AB

Part of Beijer Integrator Group


 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC - 7 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to: