亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 BitArray 轉換為字節

將 BitArray 轉換為字節

C#
HUX布斯 2023-08-13 09:38:20
BitArray我有一個將值轉換為值的代碼byte[]。我也從 stackoverflow 獲得了代碼。代碼運行得很好,我只是不明白一部分。當代碼復制到BitArray使用Byte讀取BitArray.CopyTo()時byte按LSB 順序。有人可以幫我理解為什么轉換后的字節是 LSB 順序嗎?strBit (is a string value that consists of 1/0)byte[] myByte = new byte[50];List<string> list = Enumerable.Range(0, strBit.Length / 8)    .Select(i => strBit.Substring(i * 8, 8))    .ToList();for (int x = 0; x < list.Count; x++){    BitArray myBitArray = new BitArray(list[x].ToString().Select(c => c == '1').ToArray());    myBitArray.CopyTo(myByte, x);}示例輸出:  strBit[0] = 10001111  (BitArray)轉換為字節時:  myByte[0] = 11110001 (Byte) (241/F1)
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

因為我們從右邊開始計算位,從左邊開始計算項目;例如對于


 BitArray myBitArray = new BitArray(new byte[] { 10 });

我們有(byte 10從右數):


 10 = 00001010 (binary)

            ^

            second bit (which is 1)

當相應數組的項目我們從左邊開始計數時:


 {false, true, false, true, false, false, false, false}

           ^

           corresponding second BitArray item (which is true)

這就是為什么如果我們想要一個byte后面的數組,我們必須Reverse每個byte表示,例如Linq解決方案


  using System.Collections;

  using System.Linq;


  ...


  BitArray myBitArray = ...


  byte[] myByte = myBitArray

    .OfType<bool>()

    .Select((value, index) => new { // into chunks of size 8

       value,

       chunk = index / 8 })

    .GroupBy(item => item.chunk, item => item.value)

    .Select(chunk => chunk // Each byte representation

      .Reverse()           // should be reversed   

      .Aggregate(0, (s, bit) => (s << 1) | (bit ? 1 : 0)))

    .Select(item => (byte) item)

    .ToArray();


查看完整回答
反對 回復 2023-08-13
  • 1 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號