java—如何提取lsb并将其保存到字节数组中?

91zkwejq  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(544)

我在下面函数中的意图是从文件的每个字节中提取最低有效位,并将其存储到字节数组中,但我一直在努力做到这一点。
在while循环中,我通过 & 然后我想把这个提取出来的位加到字节数组中。我不确定索引和将提取的位“附加”到数组中。

  1. public byte[] extractLSB(File file, int size) {
  2. FileInputStream fileInputStream = null;
  3. byte[] lsbByteArray = new byte[size];
  4. int arrayOffset = 0;
  5. int dataByte, extractedLSB;
  6. byte clearingByte = (byte) 0x01; // 0000 0001
  7. try {
  8. fileInputStream = new FileInputStream(file);
  9. // Read byte by byte from the file input stream
  10. while ((dataByte = fileInputStream.read()) != -1) {
  11. // extract lsb and save it to the lsbByteArray
  12. /*
  13. //I've been trying something like this
  14. extractedLSB = dataByte & clearingByte; // ? get lsb
  15. lsbByteArray[arrayOffset] <<= 1; // make space for a new bit
  16. lsbByteArray[arrayOffset] |= extractLSB; // "append" the lsb bit
  17. arrayOffset++;
  18. */
  19. }
  20. fileInputStream.close();
  21. } catch (Exception exception) {
  22. exception.printStackTrace();
  23. }
  24. return lsbByteArray;
  25. }

提前感谢您的帮助。

mgdq6dx1

mgdq6dx11#

您可以在while循环中使用字节计数器,除以8来查找字节索引,并使用模块8来查找位位置。
例如

  1. extractedLSB = dataByte & (byte) 1;
  2. lsbByteArray[counter/8] |= ( extractedLSB << (counter % 8));
  3. counter++;

这里我在数组中每8个源字节使用一个字节,因此counter/8来查找索引,字节中的位置是该除法的剩余部分,所以我执行shift extractedlsb<<(counter%8),最后还是用字节中已存储的其他位来计算结果。

相关问题