Thread: convert string to bytearray.

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    58

    convert string to bytearray.

    hi,
    i used one method.
    here is snippet code as following.
    Code:
    private byte[] HexStringToByteArray(string s)
    private byte[] HexStringToByteArray(string s)
        {
          s = s.Replace(" ", "");
          byte[] buffer = new byte[s.Length / 2];
          for (int i = 0; i < s.Length; i += 2)
            buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
          return buffer;
        }
    but i can see some error when i writing string like "(5" as parameter.
    so i tried to check this error and i'v got issue.
    if parameter is number, it works but if it is character, it doesn't work.
    how can i fix it?
    how can i change this code?
    regards.

  2. #2
    Registered User valaris's Avatar
    Join Date
    Jun 2008
    Location
    RING 0
    Posts
    507
    You can use
    Encoding.ASCII.GetBytes();

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    I'd use Encoding.UTF8.GetBytes() instead.

    If the input is pure ASCII (the first 128 characters of the classic ASCII set) then UTF-8 and ASCII are identical.

    However, if the input contains characters that are non-ASCII (such as will exist in pretty much every language -- even English may often use non-ASCII characters in loanwords, such as fiancée, naïve, etc.) your system can handle them all without an issue.


    And to the original poster: that code above is converting a string that is supposed to be a hexadecimal number. For example, it would convert:

    "F4327AB8D8F2" to the byte sequence {0xF4, 0x32, 0x7A, 0xB8, 0xD8 0xF2}

    It's not made to convert any old string; it expects a string purely of hex characters.
    Last edited by Cat; 04-23-2009 at 03:27 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  2. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 10:37 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 07:49 PM
Website Security Test