java - 将字节数组的字节转换为位并存储在整数数组中

标签 java arrays string byte bit

我在字节数组中有字节。我需要将每个字节的位值存储在一个整数数组中。

例如,

字节数组是

byte HexToBin[] = {(byte)0x9A, (byte)0xFF,(byte) 0x05,(byte) 0x16};

那么整数数组应该有

a = [10011010111111110000010100010110]

我尝试了以下代码,我能够打印每个字节(s2)的二进制值,但无法存储在整数数组 allBits 中。

byte hexToBin[] = {(byte)0x9A, (byte)0xFF,(byte) 0x05,(byte) 0x16};
int[] allBits = new int[32];
int a =0;

for (int i =0; i < hexToBin.length ; i++)
{
  byte eachByte = hexToBin[i];
  String s2 = String.format("%8s", Integer.toBinaryString((eachByte)& 0xFF)).replace(' ', '0');
  System.out.println(s2);
  char [] totalCharArr = s2.toCharArray();
  for (int k=0; k <8; k++)
  {
      allBits[k+a]= totalCharArr[k];
  }
  a= a+8;
}

for (int b=0; b<32;b++)
{
  System.out.print(allBits[b]);
}

上面代码的输出是

10011010
11111111
00000101
00010110
4948484949484948494949494949494948484848484948494848484948494948

整数数组没有二进制值。

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

感谢您的帮助

更正后的代码是

byte hexToBin[] = {(byte)0x9A, (byte)0xBF,(byte) 0x05,(byte) 0x16};
int[] allBits = new int[32]; // no of bits is determined by the license code

 for (int n =0; n<hexToBin.length; n++)
  {
    //Use ints to avoid any possible confusion due to signed byte values
    int sourceByte = 0xFF &(int)hexToBin[n];//convert byte to unsigned int
    int mask = 0x80;
    for (int i=0; i<8; i++)
    {
      int maskResult = sourceByte & mask;  // Extract the single bit
      if (maskResult>0) {
           allBits[8*n + i] = 1;
      }
      else {
           allBits[8*n + i] = 0;  // Unnecessary since array is initiated to zero but good documentation
      }
      mask = mask >> 1;
    }
  }


for (int k= 0; k<32; k++)
{
  System.out.print(allBits[k]);
}

最佳答案

假设位于 n = 0 到 3 的循环内

// Use ints to avoid any possible confusion due to signed byte values
int sourceByte = 0xFF & (int)(hexToBin[n]);  // Convert byte to unsigned int
int mask = 0x80;
for (int i = 0; i < 8; i++) {
    int maskResult = sourceByte & mask;  // Extract the single bit
    if (maskResult != 0) {
         allBits[8*n + i] = 1;
    }
    else {
         allBits[8*n + 1] = 0;  // Unnecessary since array is inited to zero but good documention
    }
    mask = mask >> 1;
}

关于java - 将字节数组的字节转换为位并存储在整数数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127514/

相关文章:

java - 错误 : package org. apache.commons.collections15 不存在

Java - 使库类具有可比性

java - JBake 're-bake' 页面是否已经是 'baked' ?

c - 逐行读取直到找到整数 C

ios - iOS wchar_t 的字节序是什么?

java - 每次我使用格式化程序写入txt时,以前写入的内容都会被删除?如何避免这种情况?

python - 如何从 pygame.surface 获取 RGB 颜色的 numpy 数组

arrays - NET中的Array.Join?

c - 传递给函数的 wchar_t 数组

python - 根据条件 pandas 数据框列删除字符串