【问题标题】:How to convert a character into a 8-bit binary number and returns the result as a string如何将字符转换为 8 位二进制数并将结果作为字符串返回
【发布时间】:2016-11-10 23:59:10
【问题描述】:

到目前为止,我有这个方法,但我不确定它是否正确....但是我如何将字符转换为 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 "";
   }

【问题讨论】:

  • 检查 Integer.toBinaryString(x)
  • 虽然您无疑将从本练习中学到东西,但您应该知道char 是一个 16 位值,并且某些字符(例如 ????)可能需要两个不可分割的 char 值才能是完整的。

标签: java binary ascii


【解决方案1】:

来了。高度优化。

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 中有一些方法可以做到这一点,但由于我不确定您为什么要对其进行编码(也许是学习?),所以我创建了这些方法。

【讨论】:

    猜你喜欢
    • 2023-03-02
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2010-09-06
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多