Ian Boyd
Ian Boyd

Reputation: 257001

How to set the high-nibble of a Byte?

Given a Byte (e.g. 0x49), i want to change the high-nibble from 4 to 7.

That is:

0x490x79

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:

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.

Upvotes: 0

Views: 1390

Answers (1)

Dean Goodman
Dean Goodman

Reputation: 983

Bit manipulating a Byte returns an Int32:

  • Byte & ByteInt32
  • Byte | ByteInt32

So you need to cast in order to not have your intermediate expressions be interpreted as an int:

Byte b = 0x49;
b = (Byte)(b & 0x0f);
b = (Byte)(0x70 | b);

Or simply:

Byte b = 0x49;
b = (Byte)(0x70 | (b & 0x0f));

Upvotes: 2

Related Questions