简体   繁体   中英

Convert python byte in string format to byte array in c#

In my python code i have a value in byte code, whenever print that byte code it will give something like this,

b'\xe0\xb6\x9c\xe0\xb7\x92\xe0\xb6\xb1\xe0\xb7\x8a\xe0\xb6\xaf\xe0\xb6\xbb'

now, that value in string format in c# that is,

string byteString = "b'\xe0\xb6\x9c\xe0\xb7\x92\xe0\xb6\xb1\xe0\xb7\x8a\xe0\xb6\xaf\xe0\xb6\xbb'";

so question is how can i convert that byteString to byte array in c#

but, my actual problem is i have a string value in python which is not in English, when i run the python code it will print the string(in non English, work fine). But, whenever run that python code in c# from process class it work fine for English and i can get the value. but it not working for non English characters, it was a null value. therefore, in python if i print that non English value in byte code i can get the value in c#. problem is how can i convert that in byte code into byte array in c#.

First, you want to modify your string slightly for usage in C#.

var str = "\xe0\xb6\x9c\xe0\xb7\x92\xe0\xb6\xb1\xe0\xb7\x8a\xe0\xb6\xaf\xe0\xb6\xbb";

You can then get your bytes fairly easily with LINQ.

var bytes = str.Select(x => Convert.ToByte(x)).ToArray();

An odd case that can occur with trying to use byte strings between Python and C# is that python will sometimes put out straight ASCII characters for certain byte values, leaving you with a mixed string like b'\\xe0ello' . C# recognizes \\x## , but it also attempts to parse \\x#### , which will tend to break when dealing with the output of a python bytestring that mixes hex codes and ascii.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM