How to getbybytes from a string?

I have a string variable from which I get the following bytes with the following loop:

Bytes I get: 1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c With that loop: byte[] temp = new byte[source.Length]; string x = ""; for (int i = 0;i != source.Length;i++) { temp[i] = ((byte) source[i]); } 

Now I wanted to simplify this operation and use Encoding GetBytes. The problem is that I cannot fit the appropriate encoding. For example, I am mistaken in a few bytes:

 Encoding.ASCII.GetBytes(source): 1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f Encoding.Default.GetBytes(source): 1e 05 55 3c e2 3f 6f 03 3f 1a 1d f4 51 6a 5e 3a ce 4e 04 3f 

How can I get rid of this loop and use Encoding GetBytes?

Here is a summary:

 Loop(correct bytes): 1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c Encoding.ASCII.GetBytes(source): 1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f Encoding.Default.GetBytes(source): 1e 05 55 3c e2 3f 6f 03 3f 1a 1d f4 51 6a 5e 3a ce 4e 04 3f 

Thanks!

Addition:

I have a string input in hex, sth, for example: "B1807869C20CC1788018690341" then I transfer this to a string using the method:

 private static string hexToString(string sText) { int i = 0; string plain = ""; while (i < sText.Length) { plain += Convert.ToChar(Convert.ToInt32(sText.Substring(i, 2), 16)); i += 2; } return plain; } 
+4
source share
2 answers

Your hexToString transfers byte values ​​(through hexadecimal) directly to Unicode code points in the range 0-255. How this happens is related to code page 28591, so if you use:

 Encoding enc = Encoding.GetEncoding(28591); 

and use enc , you should get the correct data; however, the more important point here is that binary data does not match text data, and you should not use string to store an arbitrary binary file.

+3
source

Assuming you are trying to "decode" a string literal:
C # stores strings as Unicode inside. That way you can use an encoding that (correctly) supports Unicode

eg:

 Encoding.UTF8.GetBytes(source) Encoding.UnicodeEncoding.GetBytes(source) 

Note the caution given for Encoding.Default on MSDN

+2
source

Source: https://habr.com/ru/post/1384061/


All Articles