在字节数组中逐位递增(C#)
Incrementing bit by bit in byte array (C#)
我有一个两个字节的字节数组,用作计数器。我需要一点一点地增加它,如:
0000 0000 0000 0000
0000 0000 0000 0001
0000 0000 0000 0010
0000 0000 0000 0011
.
.
.
0000 0000 1111 1111
0000 0001 1111 1111
0000 0010 1111 1111
0000 0011 1111 1111
最干净的方法是什么?
编辑
抱歉这个超级愚蠢的问题,我看错了。如果以后有人遇到同样的愚蠢问题:如评论中所述,更简单的方法是增加 Int16。
您可以只将两个字节转换为 Int16,附加您想要的位,然后返回到字节数组:
byte[] byteArray = new byte[2] { 10, 20 }; // your byte array
Int16 yourNumber = BitConverter.ToInt16(byteArray, 0); // converts your byte array to int16
yourNumber ++; // increments 1, which will do all the calculations for incrementing the bit(s) and handles overflow...
byte[] getBytes = BitConverter.GetBytes(yourNumber); // converts the int16 to byte array (I think you should be using Int16, unless you really need to use a byte array)
我不确定你到底在请求什么,如果你只想向 2 字节数组追加一点,我认为这是最快的方法。
我有一个两个字节的字节数组,用作计数器。我需要一点一点地增加它,如:
0000 0000 0000 0000
0000 0000 0000 0001
0000 0000 0000 0010
0000 0000 0000 0011
.
.
.
0000 0000 1111 1111
0000 0001 1111 1111
0000 0010 1111 1111
0000 0011 1111 1111
最干净的方法是什么?
编辑
抱歉这个超级愚蠢的问题,我看错了。如果以后有人遇到同样的愚蠢问题:如评论中所述,更简单的方法是增加 Int16。
您可以只将两个字节转换为 Int16,附加您想要的位,然后返回到字节数组:
byte[] byteArray = new byte[2] { 10, 20 }; // your byte array
Int16 yourNumber = BitConverter.ToInt16(byteArray, 0); // converts your byte array to int16
yourNumber ++; // increments 1, which will do all the calculations for incrementing the bit(s) and handles overflow...
byte[] getBytes = BitConverter.GetBytes(yourNumber); // converts the int16 to byte array (I think you should be using Int16, unless you really need to use a byte array)
我不确定你到底在请求什么,如果你只想向 2 字节数组追加一点,我认为这是最快的方法。