嘿,我想写一个像XNA Color结构或SurfaceFormat.Bgra4444结构这样的结构,它在一个8位字节中包含2个半字节。
这就是我目前所知道的..。
/// <summary>
/// Packed byte containing two 4bit values
/// </summary>
public struct Nibble2 : IEquatable<Nibble2>
{
private byte packedValue;
public byte X
{
get { return 0; }
set { }
}
public byte Y
{
get { return 0; }
set { }
}
/// <summary>
/// Creates an instance of this object.
/// </summary>
/// <param name="x">Initial value for the x component.</param>
/// <param name="y">Initial value for the y component.</param>
public Nibble2(float x, float y)
{
packedValue = 0;
}
/// <summary>
/// Creates an instance of this object.
/// </summary>
/// <param name="vector">Input value for both components.</param>
public Nibble2(Vector2 vector)
{
packedValue = 0;
}
public static bool operator ==(Nibble2 a, Nibble2 b) { return a.packedValue == b.packedValue; }
public static bool operator !=(Nibble2 a, Nibble2 b) { return a.packedValue != b.packedValue; }
public override string ToString()
{ return packedValue.ToString("X : " + X + " Y : " + Y, CultureInfo.InvariantCulture); }
public override int GetHashCode()
{return packedValue;}
public override bool Equals(object obj)
{
if (obj is Nibble2)
return Equals((Nibble2)obj);
return false;
}
public bool Equals(Nibble2 other)
{return packedValue == other.packedValue;}
}正如你所看到的,我的属性和构造器并没有被隐含。因为这是我遇到麻烦的部分。
感谢您能提供的任何帮助。
发布于 2012-07-23 15:23:24
基本上,你只需要记住什么是最高和最低的半边。仅通过用二进制1111 (十进制15)进行掩码即可获得低位半字节。高半字节可以通过右移4得到(因为byte是无符号的),剩下的只是位数学运算。
// assume x is the low nibble
public byte X
{
get { return (byte)(packedValue & 15); }
set { packedValue = (packedValue & 240) | (value & 15); }
}
// assume y is the high nibble
public byte Y
{
get { return (byte) (packedValue >> 4); }
set { packedValue = (value << 4) | (packedValue & 15); }
}然而,我不能帮助你:
public Nibble2(float x, float y)
{
packedValue = 0;
}因为这是64位,并且您希望将其放入8位。您需要成为lot,更具体地说明您想要如何处理这些值。
发布于 2012-07-23 15:10:45
考虑以下字节值:
10101100 要读取字节的高位,应将字节向右移动:
10101100 (original)
01010110 (shifted one bit)
00101011
00010101
00001010 (shifted four bits)可以使用return (byte)(packedValue >> 4);来移位字节
要只读取低位,只需使用AND运算删除最高位:
10101100
00001111 AND
--------
00001100可以使用return (byte)(packedValue & 0xf);对值执行此AND运算
设置这些值可以通过清除目标半字节,然后简单地添加输入值来执行(如果设置高半字节,则向左移位):
packedValue = (byte)((packedValue & 0xf0) + (lowNibble & 0xf));
packedValue = (byte)((packedValue & 0xf) + (highNibble << 4));发布于 2012-07-23 15:10:49
如果你和输入值用字节填充,像这样的00001111,它是15 in dec。你保留了你想保存的部分。然后你将不得不左移你的Nibble2的4个字节来存储在packedValue字节中。
private byte x = 0;
private byte y = 0;
public byte X
{
get { return x; }
set { x = value}
}
public byte Y
{
get { return y; }
set { y = value }
}
private byte packedValue
{
get { return (x & 15 << 4) | (y & 15); }
}https://stackoverflow.com/questions/11607848
复制相似问题