C#语言:在一个字节改变前四位 [英] C# Language: Changing the First Four Bits in a Byte

查看:262
本文介绍了C#语言:在一个字节改变前四位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了利用充分发挥其潜能的一个字节,我试图存储两个唯一值成一个字节:一个在第4位,另一个在第二个4位。不过,我发现,虽然这种做法可以优化内存分配,它使改变存储在字节困难单个值。

在我的code,我想改变该第一组的四个比特中的一个字节,同时保持在相同的字节中的第二四比特的值。虽然位运算让我轻松地检索和操作的前四个位值,我发现很难用一个字节中的第二组中的四位串联这个新的价值。现在的问题是,如何从一个字节擦除前四位(或者,更准确地说,将它们全部为零),并添加4位新集,以取代刚刚抹去了4位,从而$ ​​P $ pserving最后4位中的一个字节,同时改变前四个

下面是一个例子:

  //改变前四位中的一个字节的参数值
公共无效changeFirstFourBits(字节newFirstFour)
{
    //如果'newFirstFour是0101二进制,使价值01011111二进制,改变
    //前四位,但只留下了第二个四年。
}私人字节值= 255; //二进制:11111111


解决方案

使用按位AND(&安培; )来清除旧位,新位转移到正确的位置,按位或( | )在一起:

 值=(价值&安培; 0xF的)| (newFirstFour&下; 4;);

下面是发生了什么:

 值:ABCDEFGH
                       newFirstFour:0000xyzw                               0xF的:00001111
                       值放大器; 0xF的:0000efgh
                  newFirstFour<< 4:xyzw0000
(价值&安培; 0xF的)| (newFirstFour&下; 4;):xyzwefgh

In order to utilize a byte to its fullest potential, I'm attempting to store two unique values into a byte: one in the first four bits and another in the second four bits. However, I've found that, while this practice allows for optimized memory allocation, it makes changing the individual values stored in the byte difficult.

In my code, I want to change the first set of four bits in a byte while maintaining the value of the second four bits in the same byte. While bitwise operations allow me to easily retrieve and manipulate the first four bit values, I'm finding it difficult to concatenate this new value with the second set of four bits in a byte. The question is, how can I erase the first four bits from a byte (or, more accurately, set them all the zero) and add the new set of 4 bits to replace the four bits that were just erased, thus preserving the last 4 bits in a byte while changing the first four?

Here's an example:

//  Changes the first four bits in a byte to the parameter value
public void changeFirstFourBits(byte newFirstFour)
{
    //  If 'newFirstFour' is 0101 in binary, make 'value' 01011111 in binary, changing
    //  the first four bits but leaving the second four alone.
}

private byte value = 255; // binary: 11111111

解决方案

Use bitwise AND (&) to clear out the old bits, shift the new bits to the correct position and bitwise OR (|) them together:

value = (value & 0xF) | (newFirstFour << 4);

Here's what happens:

                       value        : abcdefgh
                       newFirstFour : 0000xyzw

                               0xF  : 00001111
                       value & 0xF  : 0000efgh
                  newFirstFour << 4 : xyzw0000
(value & 0xF) | (newFirstFour << 4) : xyzwefgh

这篇关于C#语言:在一个字节改变前四位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆