简体   繁体   English

如何在 C# 中实现 Python `to_bytes` 编码?

[英]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#.我想达到与 Python 方法to_bytes在 C# 中提供的相同结果。

When used in Python such as用在Python如

(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#.我无法在 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.在 C# 中,与to_bytes最接近的是BitConverter.GetBytes方法,而与from_bytes最接近的是BitConverter.To{NumericType}方法。

Here is how your example translates to C#:以下是您的示例如何转换为 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 .因为我们可能会遇到XY 问题

you can use BitConverter.您可以使用 BitConverter。 Hoever that would return an array.然而,这将返回一个数组。

as in如在

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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