C# 如何从字节中读取前 4 位和后 4 位?
问问题
32150 次
4 回答
34
使用按位AND
和移位,如下所示:
byte b = 0xAB;
var low = b & 0x0F;
var high = b >> 4;
于 2013-04-09T10:38:05.303 回答
5
我宁愿简单地使用这个 -
byte a = 68;
byte high_bits = a>>4;
byte low_bits = a&15;
于 2017-10-09T14:41:52.783 回答
2
在一个方便的结构中:
用法
var hb = new HalvedByte(5, 10);
hb.Low -= 3;
hb.High += 3;
Console.Write(string.Format("{0} / {1}", hb.Low, hb.High));
// 2, 13
代码
public struct HalvedByte
{
public byte Full { get; set; }
public byte Low
{
get { return (byte)(Full & 0x0F); }
set
{
if (value >= 16)
{
throw new ArithmeticException("Value must be between 0 and 16.");
}
Full = (byte)((High << 4) | (value & 0x0F));
}
}
public byte High
{
get { return (byte)(Full >> 4); }
set
{
if (value >= 16)
{
throw new ArithmeticException("Value must be between 0 and 16.");
}
Full = (byte)((value << 4) | Low);
}
}
public HalvedByte(byte full)
{
Full = full;
}
public HalvedByte(byte low, byte high)
{
if (low >= 16 || high >= 16)
{
throw new ArithmeticException("Values must be between 0 and 16.");
}
Full = (byte)((high << 4) | low);
}
}
奖励:数组(未经测试)
如果您需要使用这些半字节的数组,这将简化访问:
public class HalvedByteArray
{
public int Capacity { get; private set; }
public HalvedByte[] Array { get; private set; }
public byte this[int index]
{
get
{
if (index < 0 || index >= Capacity)
{
throw new IndexOutOfRangeException();
}
var hb = Array[index / 2];
return (index % 2 == 0) ? hb.Low : hb.High;
}
set
{
if (index < 0 || index >= Capacity)
{
throw new IndexOutOfRangeException();
}
var hb = Array[index / 2];
if (index % 2 == 0)
{
hb.Low = value;
}
else
{
hb.High = value;
}
}
}
public HalvedByteArray(int capacity)
{
if (capacity < 0)
{
throw new ArgumentException("Capacity must be positive.", "capacity");
}
Capacity = capacity;
Array = new HalvedByte[capacity / 2];
}
}
于 2015-10-24T01:22:56.330 回答
0
简单的方法来做到这一点。
示例使用:
答:10101110
乙:00001110
从 A 获取最后 4 位,这样输出就像 B
getBitRange(10101110, 0, 4);
//gets a bits from a byte, and return a byte of the new bits
byte getBitRange(byte data, int start, int _end){
//shift binary to starting point of range
byte shifted = (data >> start);
//calculate range length (+1 for 0 index)
int rangeLength = (_end-start)+1;
//get binary mask based on range length
byte maskBinary;
switch (rangeLength){
case 1: maskBinary = 0b00000001; break;
case 2: maskBinary = 0b00000011; break;
case 3: maskBinary = 0b00000111; break;
case 4: maskBinary = 0b00001111; break;
case 5: maskBinary = 0b00011111; break;
case 6: maskBinary = 0b00111111; break;
case 7: maskBinary = 0b01111111; break;
case 8: maskBinary = 0b11111111; break;
default:
// default statements
Serial.println("Error: Range length too long!!");
}
//cancel out
byte finalByte = (shifted & maskBinary);
return finalByte;
}
于 2020-10-26T09:44:01.160 回答