我正在研究c# desktop application
。我有一个字符串,我想toggle
。
c3 = DecimalToBinary(Convert.ToInt32(tbVal3.Text)).PadLeft(16, '0');
// above c3 is 0000001011110100
将上述字符串分成两个(子字符串)
string part1 = c3.Substring(0, 8); // 00000010
string part2 = c3.Substring(8, 8); // 11110100
对于part1
,第一个八位位组的MSB应设置为1,而对于part2
,此位应移入第一个八位位组的LSB,第二(最后)个八位位组的MSB应设置为0,因此该位应移入第一个字节的LSB。这给出了二进制part1 = 10000101
和part2 = 01110100
我已经检查了此解决方案Binary array after M range toggle operations,但仍然无法理解。
规则
in the case of the application context name LN referencing with no ciphering
the arc labels of the object identifier are (2, 16, 756, 5, 8, 1, 1);
• the first octet of the encoding is the combination of the first two
numbers into a single number, following the rule of
40*First+Second -> 40*2 + 16 = 96 = 0x60;
• the third number of the Object Identifier (756) requires two octets: its
hexadecimal value is 0x02F4, which is 00000010 11110100, but following the above rule,
the MSB of the first octet shall be set to 1 and the MSB of the second (last) octet shall
be set to 0, thus this bit shall be shifted into the LSB of the first octet. This gives
binary 10000101 01110100, which is 0x8574;
• each remaining numbers of the Object Identifier required to be encoded on one octet;
• this results in the encoding 60 85 74 05 08 01 01.
如何使用二进制字符串执行此切换?
任何帮助将不胜感激
答案 0 :(得分:0)
您可以将字符串转换为字节,以便能够操作位,然后将值转换为字符串。
因此您可以使用此:
// Convert string of binary value (base 2) to byte
byte v1 = Convert.ToByte("00000010", 2);
byte v2 = Convert.ToByte("11110100", 2);
// Operate bits
v1 = (byte)( v1 | 0b10000000 );
v1 = (byte)( v1 | ( v2 & 0b10000000 ) >> 7 );
v2 = (byte)( v2 & ~0b10000000 );
// Convert to string formatted
string result1 = Convert.ToString(v1, 2).PadLeft(8, '0');
string result2 = Convert.ToString(v2, 2).PadLeft(8, '0');
Console.WriteLine(result1);
Console.WriteLine(result2);
结果:
10000011
01110100
它强制第1部分的MSB。
它将part2的MSB复制到part1的LSB。
清除了part2的MSB。
如果您不使用C#7,请使用128
代替0b10000000
。
根据您的要求,如果我理解您的要求。但是你说: part1 = 10000101和part2 = 01110100 ...所以我不明白你写的是什么,但是也许有一个错误,你想写10000011
而不是{{ 1}}。
如果要切换位(0 => 1和1 => 0),请使用:
10000101
它切换part1的MSB。
它将part2的MSB复制到part1的LSB。
它将切换第2部分的MSB。