如何将字符转换为8位二进制数并将结果作为字符串返回

时间:2016-11-10 23:59:10

标签: java binary ascii

到目前为止,我有这种方法,我不确定它是否正确....但我如何将一个字符转换为一个8位二进制数并将结果作为字符串返回?

 //method converts a 8-bit binary number into a character and returns the character


public static char convertToString(String binary)
  {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a series of binary numbers");
  binary = input.next();


  int len = binary.length();
  int sum = 0;
  for(int i = 0; i < len; i++)
   {
      System.out.print(binary.charAt(len-i-1) + " ");
      char temp = binary.charAt(len-i-1);
      int a = Character.getNumericValue(temp);
      int value = (int)(a * Math.pow(2, i));
      System.out.println(value);
      sum +=value;
     }
    char word = (char)sum;
    return word;
   }


  public static String convertToBinary(char character)
   {

    return "";
   }

1 个答案:

答案 0 :(得分:0)

在这里。高度优化。

public static int binaryToValue(String binary)
{
   int sum = 0;
   int bit = 0;
   for (int i = binary.length(); --i >= 0;)
   {
      char temp = binary.charAt(i);
      int v = temp - '0';
      sum += v << bit;
      bit++;
   }
   return sum; // you may change the return type to char and cast this as return (char)sum
}


    public static String valueToBinary(char character)
    {
       char []ret = {'0','0','0','0','0','0','0','0'};
       int v = (int)character & 0xFFFF;
       //System.out.println(v);
       for (int idx = 0; v > 0; v >>= 1, idx++)
          if ((v & 1) == 1)
             ret[7-idx] = '1';
      return new String(ret);
    }


    public void initUI()
    {
       System.out.println(binaryToValue("1001"));
       System.out.println(valueToBinary('A')); // 65
       System.out.println(binaryToValue(valueToBinary('A')));

       MainWindow.exit(0);
    }

请注意,在Java中有一些方法可以做到这一点,但由于我不确定你为什么要编码它(也许可以学习?),我创建了这些方法。