如何设置一个字节的高半字节?
How to set the high-nibble of a Byte?
给定 Byte
(例如 0x49),我想将高半字节从 4
更改为 7
。
即:
0x49
→ 0x79
我试过以下方法:
Byte b = 0x49;
b = 0x70 | (b & 0x0f);
但是编译失败:
Compilation error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
我做错了什么?
CMRE
using System;
public class Program
{
public static void Main()
{
//The goal is to change the high nibble of 0x49 from 4 to 7. That is 0x49 ==> 0x79
Byte b = 0x49;
b = b & 0x0f;
b = 0x70 | b;
Console.WriteLine(b.ToString());
}
}
https://dotnetfiddle.net/V3bplL
我已经尝试将我能找到的每一件作品都铸造成 (Byte)
,但它仍然抱怨。我想我会得到 正确的 答案,而不是向代码发射强硬的大炮,并希望能坚持下去。
这就是示例代码不包含 (Byte)
转换的原因:
- 不需要
- 我希望其他人向我解释确切的位置和确切的原因,它或他们是或需要
因此很容易点击 dotnetfiddle
link。大家可以自己试试,加一个(Byte)
cast,看到编译不通过,去"Huh",再试试随机加更多的cast。
对于那些没有阅读的人
懒得尝试的学究们:
Byte b = (Byte)0x49;
b = ((Byte)0x70) | ((Byte)(((Byte)b) & ((Byte)((Byte)0x0f))));
也失败了。
位操作 Byte
returns 和 Int32
:
Byte
& Byte
→ Int32
Byte
| Byte
→ Int32
所以你需要强制转换,以免你的中间表达式被解释为 int
:
Byte b = 0x49;
b = (Byte)(b & 0x0f);
b = (Byte)(0x70 | b);
或者简单地说:
Byte b = 0x49;
b = (Byte)(0x70 | (b & 0x0f));
给定 Byte
(例如 0x49),我想将高半字节从 4
更改为 7
。
即:
0x49
→0x79
我试过以下方法:
Byte b = 0x49;
b = 0x70 | (b & 0x0f);
但是编译失败:
Compilation error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
我做错了什么?
CMRE
using System;
public class Program
{
public static void Main()
{
//The goal is to change the high nibble of 0x49 from 4 to 7. That is 0x49 ==> 0x79
Byte b = 0x49;
b = b & 0x0f;
b = 0x70 | b;
Console.WriteLine(b.ToString());
}
}
https://dotnetfiddle.net/V3bplL
我已经尝试将我能找到的每一件作品都铸造成 (Byte)
,但它仍然抱怨。我想我会得到 正确的 答案,而不是向代码发射强硬的大炮,并希望能坚持下去。
这就是示例代码不包含 (Byte)
转换的原因:
- 不需要
- 我希望其他人向我解释确切的位置和确切的原因,它或他们是或需要
因此很容易点击 dotnetfiddle
link。大家可以自己试试,加一个(Byte)
cast,看到编译不通过,去"Huh",再试试随机加更多的cast。
对于那些没有阅读的人
懒得尝试的学究们:
Byte b = (Byte)0x49;
b = ((Byte)0x70) | ((Byte)(((Byte)b) & ((Byte)((Byte)0x0f))));
也失败了。
位操作 Byte
returns 和 Int32
:
Byte
&Byte
→Int32
Byte
|Byte
→Int32
所以你需要强制转换,以免你的中间表达式被解释为 int
:
Byte b = 0x49;
b = (Byte)(b & 0x0f);
b = (Byte)(0x70 | b);
或者简单地说:
Byte b = 0x49;
b = (Byte)(0x70 | (b & 0x0f));