你的意思是把字符串中的字符二进制字串连成整个字符串的BinaryString?

解决方案 »

  1.   

    如果我没有理解错楼主的意思,以下是实现方法:1、把String对象转换成byte[],用getBytes方法。
    2、对每一个byte,转换成0/1序列。 // 自己写方法实现,注意Java中的byte是有符号的。
    3、把0/1序列依次合并到一起。
      

  2.   

    这是我以前写的一个转换byte到0/1序列的代码,供参考:  private static String get01String(byte b) {
        byte[] res = new byte[8];
        if (b<0) {
          b=(byte)-b;
          res[0]=1;
        }
        else res[0]=0;
        res[7] = b;
        // Converting b to 0/1 sequence
        for (int i = 7; i > 0; i--) {
          if (res[i]>1) {
            res[i-1] += res[i]/2;
            res[i] %= 2;
          }
        }
        // Copies the res array into a string
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < 8; j++) {
          sb.append(res[j]);
        }
        return sb.toString();
      }
      

  3.   

    贴错了,上面那个是老版本,还是看下面这个吧:  /**
       * This method converts byte value into 8-bit binary sequence.
       * @param byte the byte value to be converted
       * @return byte[] a 8-element byte array representing the binary sequence
       * */
      static byte[] get01Seq(byte b){
        byte[] res = new byte[8];
        for (int i = 0; i < 8; i++) {
          res[i] = (byte)(((1<<(7-i)&b)==0)?0:1);
        }
        return res;
      }转换出来的是byte[],8个元素,其中就是0/1的序列。
      

  4.   

    int i=8;  //测试数据
        String s = String.valueOf(Integer.toBinaryString(i));  //int to binary
        System.out.println(s);
        
        String ss = "11";
        int ii = Integer.parseInt(ss,2);      //binary to int,parseInt中2代表2进制,可使用2,8,10,16不同参数
        System.out.println(ii);