字节数组中逐位递增(C#)

时间:2017-09-27 11:20:51

标签: c# arrays counter bits

我有一个两个字节的字节数组,我用它作为计数器。我需要一点一点地增加它,如:

this.platform.ready().then((readySource) => {
            diagnostic.isLocationAvailable().then(
              (isAvailable) => {
                console.log('Is available? ' + isAvailable);
                this.location.getPostion();
                this.location.getCity(location.lat, location.lng);
              }).catch( (err) => {
                console.log(err);
                console.log("Please enable your location");
              });                  
          });

最干净的方法是什么?

修改

抱歉这个超级愚蠢的问题,我看错了方法。如果有人在将来遇到同样愚蠢的问题:正如评论中所提到的,更简单的方法是增加Int16。

1 个答案:

答案 0 :(得分:1)

你可以只转换Int16的两个字节,附加你想要的位,然后再回到一个字节数组:

byte[] byteArray = new byte[2] { 10, 20 }; // your byte array
Int16 yourNumber = BitConverter(byteArray, 0); // converts your byte array to int16
yourNumber ++; // appends 1 bit
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字节数组加一点,我认为这是最快的方法。