繁体   English   中英

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

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

我想达到与 Python 方法to_bytes在 C# 中提供的相同结果。

用在Python如

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

该方法返回值:

b'H\x00\x00\x00'

我无法在 C# 中找到具有相同返回值的方法。

在 C# 中,与to_bytes最接近的是BitConverter.GetBytes方法,而与from_bytes最接近的是BitConverter.To{NumericType}方法。

以下是您的示例如何转换为 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}");

现在真正的问题是:您想通过这种转换实现什么目标? 因为我们可能会遇到XY 问题

您可以使用 BitConverter。 然而,这将返回一个数组。

如在

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

暂无
暂无

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

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