C# 整数掩码为字节数组
我很困惑为什么这不起作用,有人可以提供一些见解吗?
我有一个函数正在接收整数值,但希望将十六进制值的高两位存储到字节数组元素中。
假设距离是 (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
?
?
这似乎您应该使用 BitConverter.GetBytes - 它将提供更简单的选择。
This seems like you should be using BitConverter.GetBytes - it will provide a much simpler option.
_data[1]
得到0
的原因是,当转换为byte
时,高 3 个字节会丢失。您的中间结果如下所示:
当将其转换为字节时,您仅保留低位字节:
您需要移动 8 位:
在转换为
byte
并分配给_data 之前[1]
The reason you get
0
for_data[1]
is that the upper 3 bytes are lost when you cast tobyte
.Your intermediate result looks like this:
When this is converted to a byte, you only retain the low order byte:
You need to shift by 8 bits:
before you cast to
byte
and assign to_data[1]