Q: Converting a string to byte-array without using an encoding (byte-by-byte)

D: How do I convert a string to a byte[] in .NET (C#)?
Update: Also please explain why encoding should be taken into consideration. Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

Test Case #1


File ID: #10380166-0-cc


public static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
public static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}

  1. What's ugly about this one is, that `GetString` and `GetBytes` need to executed on a system with the same endianness to work. So you can not use this to get bytes you want to turn into a string elsewhere. So I have a hard time to come up with a situations where I'd want to use this.
  2. Well, the way I think about it is: I'm not a judge. I do not ask for "evidence" from the OP to try to prove his case before I answer him (contrary to what others might try to do). He *clearly* said, "Can't I simply get what bytes the string has been stored in? Why this dependency on encoding?"", to which my answer is 100% accurate, more than the others on this page IMO. And IMO he's understood the caveats by now. Also, the fact that the answer was from 3 years ago is irrelevant. But again, if you'd rather ask for "evidence" first, then that's your style, and feel free to keep the downvote..
  3. If they can not be bothered to read the answer (or the other answers...), then I'm sorry, then there's no better way for me to communicate with them. I generally opt for answering the OP rather than trying to guess what others might do with my answer -- the OP has the right to know, and just because someone might abuse a knife doesn't mean we need to hide all knives in the world for ourselves. Though if you disagree that's fine too.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: