如何在java中将字符串转换为位流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4416954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string to a stream of bits in java
提问by Bob2
How to convert a string to a stream of bits zeroes and ones what i did i take a string then convert it to an array of char then i used method called forDigit(char,int) ,but it does not give me the character as a stream of 0 and 1 could you help please. also how could i do the reverse from bit to a char. pleaes show me a sample
如何将字符串转换为零位流和位流,我做了一个字符串,然后将其转换为字符数组,然后我使用称为 forDigit(char,int) 的方法,但它没有给我字符作为0 和 1 的流,你能帮忙吗?还有我怎么能从位到字符进行相反的操作。请给我看样品
回答by Ratna Dinakar
I tried this one ..
我试过这个..
public String toBinaryString(String s) {
char[] cArray=s.toCharArray();
StringBuilder sb=new StringBuilder();
for(char c:cArray)
{
String cBinaryString=Integer.toBinaryString((int)c);
sb.append(cBinaryString);
}
return sb.toString();
}
回答by khachik
String strToConvert = "abc";
byte [] bytes = strToConvert.getBytes();
StringBuilder bits = new StringBuilder(bytes.length * 8);
System.err.println(strToConvert + " contains " + bytes.length +" number of bytes");
for(byte b:bytes) {
bits.append(Integer.toString(b, 2));
}
System.err.println(bits);
char [] chars = new char[bits.length()];
bits.getChars(0, bits.length(), chars, chars.length);
回答by Peter Lawrey
Its easiest if you take two steps. String supports converting from String to/from byte[] and BigInteger can convert byte[] into binary text and back.
如果你采取两个步骤,它最简单。String 支持从 String 到/从 byte[] 转换,BigInteger 可以将 byte[] 转换为二进制文本并返回。
String text = "Hello World!";
System.out.println("Text: "+text);
String binary = new BigInteger(text.getBytes()).toString(2);
System.out.println("As binary: "+binary);
String text2 = new String(new BigInteger(binary, 2).toByteArray());
System.out.println("As text: "+text2);
Prints
印刷
Text: Hello World!
As binary: 10010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001
As text: Hello World!