C# 字节格式
您好,我是C#中使用字节的新手 假设我想比较基于0xxxxxxx和1xxxxxx格式的字节。我如何获得第一个比较值,同时将其从前面移除C# 字节格式,c#,byte,C#,Byte,您好,我是C#中使用字节的新手 假设我想比较基于0xxxxxxx和1xxxxxx格式的字节。我如何获得第一个比较值,同时将其从前面移除 任何帮助都将不胜感激。您需要使用二进制操作,如 a&10000 a<<1 a&10000 a我不太明白,但在C#中,要写出二进制数1000'0000,必须使用十六进制表示法。因此,要检查两个字节的最左边(最高有效)位是否匹配,您可以执行以下操作: byte a = ...; byte b = ...; if ((a & 0x80)
任何帮助都将不胜感激。您需要使用二进制操作,如
a&10000
a<<1
a&10000
a我不太明白,但在C#中,要写出二进制数1000'0000,必须使用十六进制表示法。因此,要检查两个字节的最左边(最高有效)位是否匹配,您可以执行以下操作:
byte a = ...;
byte b = ...;
if ((a & 0x80) == (b & 0x80))
{
// match
}
else
{
// opposite
}
这将使用位智能和。要清除最高有效位,可以使用:
byte aModified = (byte)(a & 0x7f);
或者,如果要再次分配回a
:
a &= 0x7f;
这将检查两个字节并比较每个位。如果位相同,则会清除该位
static void Main(string[] args)
{
byte byte1 = 255;
byte byte2 = 255;
for (var i = 0; i <= 7; i++)
{
if ((byte1 & (1 << i)) == (byte2 & (1 << i)))
{
// position i in byte1 is the same as position i in byte2
// clear bit that is the same in both numbers
ClearBit(ref byte1, i);
ClearBit(ref byte2, i);
}
else
{
// if not the same.. do something here
}
Console.WriteLine(Convert.ToString(byte1, 2).PadLeft(8, '0'));
}
Console.ReadKey();
}
private static void ClearBit(ref byte value, int position)
{
value = (byte)(value & ~(1 << position));
}
}
static void Main(字符串[]args)
{
字节字节1=255;
字节字节2=255;
对于(var i=0;i)到目前为止,你尝试了什么?你说的“从前面移除它”是什么意思?什么的前面?请澄清你的问题。我不明白你想要比较位的东西?是的,这是我要找的术语。我想要比较位。对不起,我对使用字节和位是完全陌生的。