Java中的ASCII到二进制转换程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19867918/
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
ASCii to BInary Conversion Program in java
提问by Thermaltitan
I am currently working on a project that would convert ASCii string text into Binary digits, but I've come upon several issues. First off, I would like to know exactly how can I take single digit from a String and print out it's Binary offspring, secondly What would be the best method of applying this? Thanks
我目前正在研究一个将 ASCii 字符串文本转换为二进制数字的项目,但我遇到了几个问题。首先,我想确切地知道如何从字符串中获取单个数字并打印出它的二进制后代,其次应用此方法的最佳方法是什么?谢谢
回答by constantlearner
public static String AsciiToBinary(String asciiString){
byte[] bytes = asciiString.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
// binary.append(' ');
}
return binary.toString();
}