Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Contrary to the answers here, you DON'T need to worry about encoding <strong><em>if</em></strong> the bytes don't need to be interpreted!</h2> <p>Like you mentioned, your goal is, simply, to <em>"get what bytes the string has been stored in"</em>.<br> (And, of course, to be able to re-construct the string from the bytes.)</p> <h3>For those goals, I honestly do <em>not</em> understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.</h3> <p>Just do this instead:</p> <pre><code>static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } </code></pre> <p>As long as your program (or other programs) don't try to <em>interpret</em> the bytes somehow, which you obviously didn't mention you intend to do, then there is <strong>nothing</strong> wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.</p> <h2>Additional benefit to this approach:</h2> <h3>It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!</h3> <p>It will be encoded and decoded just the same, because you are <em>just looking at the bytes</em>.</p> <p>If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload