short shortint = 5;
        String  strprint = Integer.toBinaryString(shortint);
        System.out.println(strprint);

解决方案 »

  1.   

    我经过实验发现caffv兄弟的方法存在欠缺,应该还要做一些改动才可以。因为seasun2k
    的问题是要将short形的整数转换为二进制:注意应该是16位的标准二进制。
    如果用caffv的方法,当shortint为5时将产生这样的输出
                      101  (A)
     当shortint为-5时将产生这样的输出:11111111111111111111111111111011 (B)
     这的长度为32也即是整形int的二进制格式。当然你可以对这样的输出再作处理得到正确的结果,如将(A)式的输出高位补0,将(B)式输出高16位截掉。但这样的程序速度上一定不是最优的。
      本人设计了一个这样的程序,可以实现问题解:
      public static String short2binary(short num){
    double term;
    String binaryStr="";
    if(num<0) {//这个数为负数
    num=(short)Math.abs(num);
    String negStr=short2binary(num);
    StringBuffer strBuf=new StringBuffer(negStr);//先得到这个数绝对值的二进制串
    char[] binChar={'0','1'};
    /////////////////取这个数的补码,既是这个数绝对值的二进制的补码//////////////////
    /////////////先取反码/////////////////////////////
       for (int j=0;j<=15 ;j++ ) {
          if (strBuf.charAt(j)==binChar[0]) {
                strBuf.setCharAt(j,binChar[1]);
            }
            else {
                strBuf.setCharAt(j,binChar[0]);
          }
     }
    //////////////反码家1/////////////////////////////  if (strBuf.charAt(15)==binChar[0]) {
        strBuf.setCharAt(15,binChar[1]);
        return strBuf.toString();
        }else {
        strBuf.setCharAt(15,binChar[0]);
          for (int i = 15; i>0 ; i--) {
             if (strBuf.charAt(i-1)==binChar[1]) {
                   strBuf.setCharAt(i-1,binChar[0]);
                    if (i==1) {
                        return strBuf.toString();
                      }
                        else {
                            continue;
                            }          }else{
              strBuf.setCharAt(i-1,binChar[1]);
              return  strBuf.toString();
              }      }    }
    }
    for(int i=15;i>=0;i--){//求取这个树的二进制串
       term=Math.pow(2,i);
         if(num==term){
                binaryStr+="1";
                for(int j=0;j<i;j++)  binaryStr+="0";
                return binaryStr;
          }else if(num>term){
               binaryStr+="1";
               num=(short)(num-term);
         }  else {
              binaryStr+="0";
      }
    }
     return binaryStr;
    }