如何在C#、A909中获取41104的ushort数据?

发布于 2024-09-16 19:52:36 字数 427 浏览 3 评论 0原文

我正在尝试将 int 值转换为 16 位无符号字符类型 (USHORT)。在示例中,41104 是 ushort 中的 A909,但在 C# 中,我尝试使用代码示例(在 MSDN 文章的帮助下BitConverter.GetBytes Yöntem (UInt16)):

byte[] bytes = BitConverter.GetBytes(41104);
string bytes = BitConverter.ToString(byteArray);
//It returns "90-A0"

如何获取 41104 的 ushort 形式的 A909 值?

I'm trying to convert an int value to a 16-bit unsigned char type (USHORT). In an example, 41104 is A909 in ushort, but in C# I tried with code sample as (with help from MSDN article BitConverter.GetBytes Yöntem (UInt16)):

byte[] bytes = BitConverter.GetBytes(41104);
string bytes = BitConverter.ToString(byteArray);
//It returns "90-A0"

How do I get the A909 value as ushort for 41104?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里寻她 2024-09-23 19:52:36

实际上正确的(=十六进制)值是A090。我不在乎它是否是 ushort,你想要的是显示十六进制等效值。

您提供的代码片段已经做到了这一点。一个字节是“A0”,另一个字节是“90”。你只需要把订单弄对就可以了。

另一种方法是让 .NET 完成这项工作

String.Format("{0:X}", 41104);

正如您所看到的,这并不是真正的数据转换,而是一种不同的显示方式。

Actually the correct (=hexadecimal) value is A090. I doesn't matter whether it's ushort or not, what you want is to display the hexadecimal equivalent.

The code snippet you provided already does this. One byte is "A0" the other one "90". You just have to get the order right.

Another way is to let .NET do the job

String.Format("{0:X}", 41104);

As you can see it's not really a data conversion, but rather a different way of display.

影子的影子 2024-09-23 19:52:36

您需要重新排序字节:

byte[] bytes = BitConverter.GetBytes(41104);
if (BitConverter.IsLittleEndian)
{    List<byte> tmp = new List<byte>();
     tmp.AddRange(bytes);
     tmp.Reverse();
     bytes = tmp.ToArray();
}

You need to reorder the bytes:

byte[] bytes = BitConverter.GetBytes(41104);
if (BitConverter.IsLittleEndian)
{    List<byte> tmp = new List<byte>();
     tmp.AddRange(bytes);
     tmp.Reverse();
     bytes = tmp.ToArray();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文