简体   繁体   English

长为64位二进制字符串并将其添加到8x8数组中

[英]Long to binary string as 64 bit and adding it to 8x8 array

Say, I have a binary string like 说,我有一个二进制字符串

11110001000010100000011000000110000001100000010100001000111100

it's 62 bits and I want it to be 64 它是62位,我希望是64

0011110001000010100000011000000110000001100000010100001000111100

I can print it as 64, but how do I save it so I can add it to the array? 我可以将其打印为64,但是如何保存它才能将其添加到阵列中?

for(int i = 0; i < Long.numberOfLeadingZeros((long)num); i++) {
            System.out.print('0');
        }
        System.out.println(Long.toBinaryString((long)num));

Also I want to add in the 2D array so I can display it as 8x8 我也想添加2D数组,以便可以将其显示为8x8

00111100
01000010
10000001
10000001
10000001
10000001
01000010
00111100

This is my code to add it to the array, 这是我的代码将其添加到数组中,

for(int i = 0; i < bin1.length(); i++){
            for(int j = 0; j < 8; j++){
                for(int z = 0; z < 8; z++){
                    table[j][z] = bin1.charAt(i);
                }
            }
        }

but when I print it, it just prints 0 s. 但是当我打印时,它只打印0 s。

00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000

Here you go: 干得好:

long num = 4342175383962075708L;
char[][] table = new char[8][8];
String bin1 = Long.toUnsignedString(num, 2);

while(bin1.length()<64){
  bin1="0"+bin1;
}
//Store the bits in the array
int i=0;
for(int j = 0; j < 8; j++){
    for(int z = 0; z < 8; z++){
        table[j][z] = bin1.charAt(i++);
    }
}
//Print the numbers
for(char[] m : table){
  for(char n : m){
    System.out.print(n);
  }
  System.out.println()
}

using below to save it as 2d array that you want: 在下面使用将其保存为所需的2d数组:

int j=0,z =0;
for(int i = 0; i < Long.numberOfLeadingZeros((long)num); i++) {
        System.out.print('0');
        table[j][z++] = '0';
        if(z>7){
           j++;
           z=0;
        }
}

String a = Long.toBinaryString((long)num);
for(int g = 0; g < a.length(); g++){
        table[j][z++] = a.charAt(g);
        System.out.print(a.charAt(g));
        if(z>7){
           j++;
           z=0;
        }
    }
    System.out.print("\n");
    for(int k = 0; k < 8; k++){
        for(int s = 0; s < 8; s++){
            System.out.print(table[k][s]);
        }
        System.out.print("\n");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM