Given a Byte
(e.g. 0x49), i want to change the high-nibble from 4
to 7
.
That is:
0x49
→0x79
I've tried the following:
Byte b = 0x49;
b = 0x70 | (b & 0x0f);
But it fails to compile:
Compilation error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
What am i doing wrong?
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
I've tried casting every piece i can find as (Byte)
, but it still complains. And rather than firing a hard-cast cannon at the code, and hoping something sticks, i figured i would get the correct answer.
That's why the example code contains no (Byte)
casts:
- it shouldn't be needed
- i want someone else to explain to me exactly where, and exactly why, it or they is or are needed
Hence the easy to click dotnetfiddle
link. People can try it for themselves, add a (Byte)
cast, see it fails to compile, go "Huh", and try adding more casts randomly.
For those who didn't read
For the pedants who didn't bother to try it:
Byte b = (Byte)0x49;
b = ((Byte)0x70) | ((Byte)(((Byte)b) & ((Byte)((Byte)0x0f))));
also fails.