字符串到Java中的二进制输出 [英] String to binary output in Java

查看:134
本文介绍了字符串到Java中的二进制输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中获取二进制(011001 ..),但是我得到[B @ addbf1,必须有一个简单的转换,但我看不到它。

I want to get binary (011001..) from a String but instead i get [B@addbf1 , there must be an easy transformation to do this but I don't see it.

public static String toBin(String info){
  byte[] infoBin = null;
  try {
   infoBin = info.getBytes( "UTF-8" );
   System.out.println("infoBin: "+infoBin);
  }
  catch (Exception e){
   System.out.println(e.toString());
  }
  return infoBin.toString();
}

这里我得到infoBin:[B @ addbf1

我想要infoBin:01001 ...

Here i get infoBin: [B@addbf1
and I would like infoBin: 01001...

任何帮助将不胜感激,谢谢!

Any help would be appreciated, thanks!

推荐答案

只有Integer有一个转换为二进制字符串表示形式的方法,检查出来:

Only Integer has a method to convert to binary string representation check this out:

import java.io.UnsupportedEncodingException;

public class TestBin {
    public static void main(String[] args) throws UnsupportedEncodingException {
        byte[] infoBin = null;
        infoBin = "this is plain text".getBytes("UTF-8");
        for (byte b : infoBin) {
            System.out.println("c:" + (char) b + "-> "
                    + Integer.toBinaryString(b));
        }
    }
}

将打印:

c:t-> 1110100
c:h-> 1101000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:p-> 1110000
c:l-> 1101100
c:a-> 1100001
c:i-> 1101001
c:n-> 1101110
c: -> 100000
c:t-> 1110100
c:e-> 1100101
c:x-> 1111000
c:t-> 1110100






填充:


Padding:

String bin = Integer.toBinaryString(b); 
if ( bin.length() < 8 )
  bin = "0" + bin;

这篇关于字符串到Java中的二进制输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆