Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts

    C#: How do I convert a character into ascii code, and then back into a character?

    How do I substitute a character in a string with it's ascii code, then reverse operation, substituting the ascii code with the character?

    To be more clear, I have this string:
    Code:
    "fred"
    I want to replace the character 'e' with its ascii code, either a decimal of 101 or a hex of 0x65.

    After the replacement, my string would now read:
    Code:
    "fr101d"
    or
    Code:
    "fr0x65d"
    The try part seems to converting it back. That is converting this:
    Code:
    "fr0x65d"
    back into this:
    Code:
    "fred"
    This seems like it should be fairly easy, but I can't figure it out.

    Any ideas?

    Thanks!
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #2
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    Code:
    string name = "fr0x65d";
    bool cont = name.Contains("0x65");
    if(cont == true)
        name = name.Replace("0x65", "e");

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #3
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts
    Oh common alykins, give me some credit... My situation is a little more dynamic than that. That was just the best way to make it clear. It actually iterates through a string and changes all characters that are not an int: 30 - 39, A-Z: 41 - 5A, or a-z: 61 - 7A.

    The reason I didn't throw that tidbit in, is because I didn't want anyone concerning them selves with the additional complexity...

    I've been able to convert the characters to decimals like so:
    Code:
    asciiByte = ASCIIEncoding.ASCII.GetBytes(url[i].ToString());
    decymal = asciiByte.GetValue(0).ToString();
    Using the decimals in this case would probably be preferred, but I can't figure out how to get them back to a string. Once I store the 101 as a string, it is no longer a character '101', it is now a '1', a '0', and another '1'.

    The reason I didn't mention all of that, was because I didn't want to get you into my same mind set, which hasn't been very helpful...

    I still welcome your help of course, but something a little more in depth would be better.

    Thanks!

    P.S.
    Though, I did get a good idea in writing this. We shall see how great it is though...
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #4
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts
    Okay, that idea was a flop. However, it did prompt me to try something else, which was also a flop, but lead me to something that did work...
    Code:
    decyChar = int.Parse("101"); // Convert the string into a decimal
    strChar = Convert.ToChar(decyChar).ToString(); // Convert the decimal into a character, to be converted into a string
    I new it couldn't be that difficult, it just took me a while to figure it out.

    If you know of a better solution, or even an alternate solution, I would gladly like to hear about it.

    I would still also be interested in knowing how to do this same thing with hexadecimals instead of decimals....

    Thanks!
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #5
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    i am sort of confused as to what you are trying to accomplish- I assumed you could connect the dots with that "tid bit" but I didn't know if you knew it existed; nor do I know if you know how to use msdn class lib (I will assume from this point on you do- no offense meant)...

    if you are taking a string and converting it all to byte form you should be doing a byte array not just a byte- then each string char would be a byte[] spot
    so your conversion should be
    asciiByte[] = ASCIIEncoding.ASCII.GetBytes(string);
    in turn your decimal should be another array...
    for(int i=0; i <= acsiiByte.length; i++){
    decimal[i] = .... I stopped typing in here and did a quicky in VS
    Code:
                string demo = "blah";
                byte[] _demo = ASCIIEncoding.ASCII.GetBytes(demo);
                int[] deci = new int[10];
                char[] chars = new char[10];
                string[] decimalstring = new string[10];
                for (int i = 0; i <= 10; i++)
                {
                    deci[i] = Convert.ToInt32(_demo.GetValue(i));  // straight conversion to int32 on the fly from byte array
                    decimalstring[i] = _demo.GetValue(i).ToString();  // conversion of byte array char to string
                    deci[i] = Convert.ToInt32(decimalstring[i]);  // conversion of string back to int
                    chars[i] = Convert.ToChar(deci[i]);
                }
    I do appologize for the horrible naming convenvtions- also convert.tochar() supports a lot of overload methods... does that help @ all or am I off base w/ what it is you are trying to do

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #6
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    also worth noting is the loose usage of the terminology decimal- unless you are really talking about decimal (which is a C# data type) I think you mean int

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #7
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts
    Given the 15 minute difference in timestamps between your post and mines, I will assume you didn't see my post, before posting yours. However, what you posted is pretty much exactly what I did.

    Quote Originally Posted by alykins View Post
    Code:
    string name = "fr0x65d";
    bool cont = name.Contains("0x65");
    if(cont == true)
        name = name.Replace("0x65", "e");
    I assumed you could connect the dots with that "tid bit" but I didn't know if you knew it existed;
    I'm sorry, I guess I don't see that as a "tid bit." I don't see how anyone could go from that to this:
    Quote Originally Posted by alykins View Post
    Code:
                string demo = "blah";
                byte[] _demo = ASCIIEncoding.ASCII.GetBytes(demo);
                int[] deci = new int[10];
                char[] chars = new char[10];
                string[] decimalstring = new string[10];
                for (int i = 0; i <= 10; i++)
                {
                    deci[i] = Convert.ToInt32(_demo.GetValue(i));  // straight conversion to int32 on the fly from byte array
                    decimalstring[i] = _demo.GetValue(i).ToString();  // conversion of byte array char to string
                    deci[i] = Convert.ToInt32(decimalstring[i]);  // conversion of string back to int
                    chars[i] = Convert.ToChar(deci[i]);
                }
    String.Replace() would only work if you set up an array of all hexadecimal values of each character you would want to replace. That is nothing like converting a decimal into a string.

    Quote Originally Posted by alykins View Post
    also worth noting is the loose usage of the terminology decimal- unless you are really talking about decimal (which is a C# data type) I think you mean int
    When I say decimal representation, I do not mean C#'s decimal type. I tried to make that clear, but I guess I failed. I refer to it as a decimal because every ascii chart I have seen lists the characters in octal, hexadecimal, decimal, and character.

    I still wonder how you would convert it to an octal or a hexadecimal though. There is no Convert.ToOctal() or Convert.ToHex()...
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #8
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    I'm sorry, I guess I don't see that as a "tid bit." I don't see how anyone could go from that to this:
    because in your first example you explicitly called out that you had a hex value in your code- not that you were taking a string and converting it. Once I saw "what" you were trying to do it was a lot simpler to answer you and hence the answer- You should know that you need to be converting to a byte[] and not a byte... I am pretty sure it will not throw an error on that- I do know that if it does not throw an error it will simply truncate.

    googled: hex value in C#
    googling octal value in C# gave me the same hit and below in comments is

    //C#
    //Convert.ToString(* value, Int32 ToBase)
    // * value can be of type byte (Byte), short (Int16), int (Int32) or long (Int64)
    // ToBase must be 2 (for binary), 8 (for octal), 10 (for decimal) or 16 (for hexadecimal).
    Int32 intValue = 43981;
    String hexValue = Convert.ToString(intValue, 16); //result: hexValue = "ABCD"
    // Reverse operation Convert.ToInt32(String value, Int32 FromBase)
    intVal = Convert.ToInt32(hexValue, 16);
    //Convert.ToByte(String value, FromBase), Convert.ToInt16(String value, FromBase), Convert.ToInt64(String value, FromBase)
    Edit:
    Trying to re-link; the link was broken :|
    re-link attempt
    Last edited by alykins; 01-20-2012 at 12:31 AM.

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #9
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts
    Quote Originally Posted by alykins View Post
    because in your first example you explicitly called out that you had a hex value in your code- not that you were taking a string and converting it.
    Yeah, these things happen, but still...

    Quote Originally Posted by alykins View Post
    You should know that you need to be converting to a byte[] and not a byte... I am pretty sure it will not throw an error on that- I do know that if it does not throw an error it will simply truncate.
    No, it won't even compile, it can't implicitly cast a byte[] into a byte. I have no idea what would happen if you were to explicitly cast it to a byte. Knowing MS though, it would probably blow up at run time. It should never return a byte[] with more than one value because the largest decimal ascii is small enough to be represented as one byte. However, I would rather let it take as much space as it needs, and just pull of the first value. At the moment, I am initializing byte[] to byte[1], so if it does spew out more than one byte, it will blow up. I will probably check it's size before throwing it into the array so I can return gracefully. However this is a case were it shouldn't blow up unless something really goes wrong. So, maybe I will just let it blow up?

    Quote Originally Posted by alykins View Post
    googled: hex value in C#
    googling octal value in C# gave me the same hit and below in comments is
    Code:
    //C#
    //Convert.ToString(* value, Int32 ToBase)
    // * value can be of type byte (Byte), short (Int16), int (Int32) or long (Int64)
    // ToBase must be 2 (for binary), 8 (for octal), 10 (for decimal) or 16 (for hexadecimal).
    Int32 intValue = 43981;
    String hexValue = Convert.ToString(intValue, 16); //result: hexValue = "ABCD"
    // Reverse operation Convert.ToInt32(String value, Int32 FromBase)
    intVal = Convert.ToInt32(hexValue, 16);
    //Convert.ToByte(String value, FromBase), Convert.ToInt16(String value, FromBase), Convert.ToInt64(String value, FromBase)
    Cool, thanks. I will have to look into that. I was having a hard time searching for this.
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #10
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Tl;dr but if you want to print a number out in hex there is an easy way to do that in C#:

    Code:
    int x = 16;
    string hex = x.ToString("X");
    See: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •