【问题标题】:Print String as Bytes将字符串打印为字节
【发布时间】:2011-11-28 06:42:23
【问题描述】:

谁能告诉我如何将字符串打印为字节,即其​​对应的 ASCII 码?!

我的输入是一个普通的字符串,比如“9”,输出应该是字符'9'对应的ASCII值

【问题讨论】:

    标签: java string printing byte


    【解决方案1】:

    如果您正在寻找字节数组 - 请参阅此问题:How to convert a Java String to an ASCII byte array?

    要获取每个单独字符的 ascii 值,您可以这样做:

    String s = "Some string here";
    
    for (int i=0; i<s.length();i++)
      System.out.println("ASCII value of: "+s.charAt(i) + " is:"+ (int)s.charAt(i) );
    

    【讨论】:

      【解决方案2】:

      使用String.getBytes() 方法。

      byte []bytes="Hello".getBytes();
      for(byte b:bytes)
        System.out.println(b);
      

      【讨论】:

      • 适用于 ASCII,但如果遇到 8 位半,您将得到负数,因为决定 Java 中的字节是有符号的。
      【解决方案3】:

      您好,我不确定您想要什么,但可能是以下方法有助于打印它。

          String str = "9";
      
          for (int i = 0; i < str.length(); i++) {
              System.out.println(str.charAt(i) + " ASCII " + (int) str.charAt(i));
          }
      

      你可以在http://www.java-forums.org/java-tips/5591-printing-ascii-values-characters.html看到它

      【讨论】:

        【解决方案4】:

        一种天真的方法是:

        1. 你可以遍历一个字节数组:

          final byte[] bytes = "FooBar".getBytes(); for (byte b : bytes) { System.out.print(b + " "); }

          结果:70 111 111 66 97 114

        2. 或者,通过一个 char 数组并将 char 转换为原始 int

          for (final char c : "FooBar".toCharArray()) { System.out.print((int) c + " "); }

          结果:70 111 111 66 97 114

        3. 或者,感谢 Java8,通过 inputSteam 使用 forEach: "FooBar".chars().forEach(c -&gt; System.out.print(c + " "));

          结果:70 111 111 66 97 114

        4. 或者,感谢 Java8 和 Apache Commons Langfinal List<Byte> list = Arrays.asList(ArrayUtils.toObject("FooBar".getBytes())); list.forEach(b -> System.out.print(b + " "));

          结果:70 111 111 66 97 114

        更好的方法是使用charset(ASCII、UTF-8、...):

        // Convert a String to byte array (byte[])
        final String str = "FooBar";
        final byte[] arrayUtf8 = str.getBytes("UTF-8");
        for(final byte b: arrayUtf8){
          System.out.println(b + " ");
        }
        

        结果:70 111 111 66 97 114

        final byte[] arrayUtf16 = str.getBytes("UTF-16BE");
          for(final byte b: arrayUtf16){
        System.out.println(b);
        }
        

        结果:70 0 111 0 111 0 66 0 97 0 114

        希望它有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-23
          • 2020-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多