C# 整数掩码为字节数组

发布于 2024-09-30 16:28:48 字数 507 浏览 5 评论 0原文

我很困惑为什么这不起作用,有人可以提供一些见解吗?

我有一个函数正在接收整数值,但希望将十六进制值的高两位存储到字节数组元素中。

假设距离是 (24,135)10 或 (5E47)16

public ConfigureReportOptionsMessageData(int Distance, int DistanceCheckTime)
    {
        ...
        this._data = new byte[9];
        this._data[0] = (byte)(Distance & 0x00FF); // shows 47
        this._data[1] = (byte)(Distance & 0xFF00); // shows 00
        this._data[2] = (byte)(DistanceCheckTime & 0xFF);
        ...
    }

I'm confused as to why this isn't working, can someone please provide some insight?

I have a function who is taking in an integer value, but would like to store the upper two bits of the hex value into a byte array element.

Let's say if Distance is (24,135)10 or (5E47)16

public ConfigureReportOptionsMessageData(int Distance, int DistanceCheckTime)
    {
        ...
        this._data = new byte[9];
        this._data[0] = (byte)(Distance & 0x00FF); // shows 47
        this._data[1] = (byte)(Distance & 0xFF00); // shows 00
        this._data[2] = (byte)(DistanceCheckTime & 0xFF);
        ...
    }

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

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

发布评论

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

评论(3

染柒℉ 2024-10-07 16:28:48
this._data[1] = (byte)(Distance >> 8);

this._data[1] = (byte)(Distance >> 8);

?

等风来 2024-10-07 16:28:48

这似乎您应该使用 BitConverter.GetBytes - 它将提供更简单的选择。

This seems like you should be using BitConverter.GetBytes - it will provide a much simpler option.

忘羡 2024-10-07 16:28:48

_data[1] 得到 0 的原因是,当转换为 byte 时,高 3 个字节会丢失。

您的中间结果如下所示:

Distance && 0xff00 = 0x00005e00;

当将其转换为字节时,您仅保留低位字节:

(byte)0x00005e00 = 0x00;

您需要移动 8 位:

0x00005e00 >> 8 = 0x0000005e;

在转换为 byte 并分配给 _data 之前[1]

The reason you get 0 for _data[1] is that the upper 3 bytes are lost when you cast to byte.

Your intermediate result looks like this:

Distance && 0xff00 = 0x00005e00;

When this is converted to a byte, you only retain the low order byte:

(byte)0x00005e00 = 0x00;

You need to shift by 8 bits:

0x00005e00 >> 8 = 0x0000005e;

before you cast to byte and assign to _data[1]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文