简体   繁体   中英

How can I achieve Python `to_bytes` encoding in C#?

I want to achieve the same result that the Python method to_bytes provides in C#.

When used in Python such as

(72).to_bytes(SIZEOF_INT,'little')

the method returns the value:

b'H\x00\x00\x00'

I am unable to find a method that has the same return value in C#.

In C#, the closest equivalent to to_bytes would be the BitConverter.GetBytes methods and the closest equivalent to from_bytes would be the BitConverter.To{NumericType} methods.

Here is how your example translates to C#:

int value = 72;
byte[] bytes = BitConverter.GetBytes(value);
int convertedValue = BitConverter.ToInt32(bytes);

// output: "bytes = 48 00 00 00"
Console.WriteLine($"bytes = {string.Join(" ", bytes.Select(b => b.ToString("X2")))}");

// output: "value = 72"
Console.WriteLine($"value = {convertedValue}");

Now the real question is: what are you trying to achieve with this conversion? Because we might be into a XY problem .

you can use BitConverter. Hoever that would return an array.

as in

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);

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