将二进制字符串转换为十六进制字符串 JAVA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25592084/
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
Converting binary string to a hexadecimal string JAVA
提问by dumas
I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:
我也想将我的二进制文件(在字符串中)转换为十六进制字符串,这只是一个程序片段,因为这个程序只是另一个更大程序的一部分:
//the variable name of the binary string is: "binary"
int digitNumber = 1;
int sum = 0;
int test = binary.length()%4;
if(test!=0) {
binary = padLeft(binary, test);
}
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
public static String padLeft(String s, int n) {
return String.format("%0$"+n+"s", s);
}//i added this for padding
the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:
问题是我不知道填充是否有效,但我确信这个程序返回了一个错误的二进制字符串的十六进制转换我正在尝试这样做:
http://www.wikihow.com/Convert-Binary-to-Hexadecimal
http://www.wikihow.com/Convert-Binary-to-Hexadecimal
PS: I need to implement it(not using any built-in function)
PS:我需要实现它(不使用任何内置函数)
采纳答案by Eran
If you don't have to implement that conversion yourself, you can use existing code :
如果您不必自己实现该转换,则可以使用现有代码:
int decimal = Integer.parseInt(binaryStr,2);
String hexStr = Integer.toString(decimal,16);
If you must implement it yourself, there are several problems in your code :
如果你必须自己实现它,你的代码有几个问题:
- The loop should iterate from 0 to binary.length()-1 (assuming the first character of the String represents the most significant bit).
- You implicitly assume that your binary String has 4*x charcters for some integer x. If that's not true, your algorithm breaks. You should left pad your String with zeroes to get a String of such length.
sum
must be reset to 0 after each hex digit you output.System.out.print(digitNumber);
- here you should printsum
, notdigitNumber
.
- 循环应该从 0 迭代到 binary.length()-1(假设 String 的第一个字符代表最高有效位)。
- 您隐含地假设您的二进制字符串对于某个整数 x 有 4*x 个字符。如果这不是真的,你的算法就会中断。你应该用零填充你的字符串以获得这样长度的字符串。
sum
必须在输出每个十六进制数字后重置为 0。System.out.print(digitNumber);
- 在这里你应该打印sum
,而不是digitNumber
。
Here's how the mostly fixed code looks :
以下是大多数固定代码的外观:
int digitNumber = 1;
int sum = 0;
String binary = "011110101010";
for(int i = 0; i < binary.length(); i++){
if(digitNumber == 1)
sum+=Integer.parseInt(binary.charAt(i) + "")*8;
else if(digitNumber == 2)
sum+=Integer.parseInt(binary.charAt(i) + "")*4;
else if(digitNumber == 3)
sum+=Integer.parseInt(binary.charAt(i) + "")*2;
else if(digitNumber == 4 || i < binary.length()+1){
sum+=Integer.parseInt(binary.charAt(i) + "")*1;
digitNumber = 0;
if(sum < 10)
System.out.print(sum);
else if(sum == 10)
System.out.print("A");
else if(sum == 11)
System.out.print("B");
else if(sum == 12)
System.out.print("C");
else if(sum == 13)
System.out.print("D");
else if(sum == 14)
System.out.print("E");
else if(sum == 15)
System.out.print("F");
sum=0;
}
digitNumber++;
}
Output :
输出 :
7AA
7AA
This will work only if the number of binary digits is divisable by 4, so you must add left 0
padding as a preliminray step.
只有当二进制数字的数量可以被 4 整除时,这才有效,因此您必须添加左0
填充作为初步步骤。
回答by Amit.D
You can try something like this.
你可以尝试这样的事情。
private void bitsToHexConversion(String bitStream){
int byteLength = 4;
int bitStartPos = 0, bitPos = 0;
String hexString = "";
int sum = 0;
// pad '0' to make input bit stream multiple of 4
if(bitStream.length()%4 !=0){
int tempCnt = 0;
int tempBit = bitStream.length() % 4;
while(tempCnt < (byteLength - tempBit)){
bitStream = "0" + bitStream;
tempCnt++;
}
}
// Group 4 bits, and find Hex equivalent
while(bitStartPos < bitStream.length()){
while(bitPos < byteLength){
sum = (int) (sum + Integer.parseInt("" + bitStream.charAt(bitStream.length()- bitStartPos -1)) * Math.pow(2, bitPos)) ;
bitPos++;
bitStartPos++;
}
if(sum < 10)
hexString = Integer.toString(sum) + hexString;
else
hexString = (char) (sum + 55) + hexString;
bitPos = 0;
sum = 0;
}
System.out.println("Hex String > "+ hexString);
}
Hope this helps :D
希望这会有所帮助:D
回答by rayan
import java.util.*;
public class BinaryToHexadecimal
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the binary number");
double s=sc.nextDouble();
int c=0;
long s1=0;
String z="";
while(s>0)
{
s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
s=(long)s/10;
c++;
}
while(s1>0)
{
long j=s1%16;
if(j==10)
{
z="A"+z;
}
else if(j==11)
{
z="B"+z;
}
else if(j==12)
{
z="C"+z;
}
else if(j==13)
{
z="D"+z;
}
else if(j==14)
{
z="E"+z;
}
else if(j==15)
{
z="F"+z;
}
else
{
z=j+z;
}
s1=s1/16;
}
System.out.println("The respective Hexadecimal number is : "+z);
}
}
回答by rayan
By given binary number 01011011
, we will convert it at first to decimal number, each number will be Math.pow()
by decrementd length:
根据给定的二进制数01011011
,我们首先将其转换为十进制数,每个数字的Math.pow()
长度都是递减的:
01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (1 × 2(4)) + (1 × 2(3)) + (0 × 2(2)) + (1 × 2(1)) + (1 × 2(0))
= (0 × 128) + (1 × 64) + (0 × 32) + (1 × 16) + (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)
= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1
= 91 (decimal form of binary number)
01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (1 × 2(4)) + (1 × 2(3)) + (0 × 2(2)) + (1 × 2(1)) + (1 × 2(0))
= (0 × 128) + (1 × 64) + (0 × 32) + (1 × 16) + (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)
= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1
= 91(二进制数的十进制形式)
Now after get decimal number we have to convert it to hexa-decimal-number.
现在在获得十进制数后,我们必须将其转换为十六进制数。
So, 91 is greater than 16. So, we have to divide by 16.
所以,91 大于 16。所以,我们必须除以 16。
After dividing by 16, quotient is 5 and remainder is 11.
除以 16 后,商为 5,余数为 11。
Remainder is less than 16.
余数小于 16。
Hexadecimal number of remainder is B.
余数的十六进制数是B。
Quotient is 5 and hexadecimal number of remainder is B.
商为 5,余数的十六进制数为 B。
That is, 91 = 16 × 5 +11 = B
5 = 16 × 0 + 5 = 5
=5B
即 91 = 16 × 5 +11 = B
5 = 16 × 0 + 5 = 5
= 5B
Implementation:
执行:
String hexValue = binaryToHex(binaryValue);
//Display result
System.out.println(hexValue);
private static String binaryToHex(String binary) {
int decimalValue = 0;
int length = binary.length() - 1;
for (int i = 0; i < binary.length(); i++) {
decimalValue += Integer.parseInt(binary.charAt(i) + "") * Math.pow(2, length);
length--;
}
return decimalToHex(decimalValue);
}
private static String decimalToHex(int decimal){
String hex = "";
while (decimal != 0){
int hexValue = decimal % 16;
hex = toHexChar(hexValue) + hex;
decimal = decimal / 16;
}
return hex;
}
private static char toHexChar(int hexValue) {
if (hexValue <= 9 && hexValue >= 0)
return (char)(hexValue + '0');
else
return (char)(hexValue - 10 + 'A');
}
回答by Zayeed A. Chowdhury
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stringprocessing;
/* * 要更改此许可证标题,请在项目属性中选择许可证标题。* 要更改此模板文件,请选择工具 | 模板 * 并在编辑器中打开模板。*/ 包字符串处理;
/** * * @author Zayeed Chowdhury */ public class StringProcessing {
/** * * @author Zayeed Chowdhury */ public class StringProcessing {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int index = 0;
String bin = "0000000101100101011011100110011100000001000000000000000010101010010101100110010101100011011010010110110101100001001000000100111001100101011101000111011101101111011100100110101101110011001000000100100001000001010100110010000001001001010100110101001101010101010001010100010000100000010000010010000001010010010001010101000101010101010010010101001001000101010001000010000001010111010001010100010101001011010011000101100100100000010101000100010101010011010101000010000001000110010011110101001000100000010101000100100001000101001000000100011001001111010011000100110001001111010101110100100101001110010001110010000001000011010011110101010101001110010101000100100101000101010100110010111101000001010100100100010101000001010100110011101000100000010100000110100101101110011000010110110000101100001000000100000101011010001110110010000001000001010101000010000000000001111000000011000100110010001110100011000100110011001000000101000001001101001000000100111101001110";
String[] hexString = new String[bin.length() / 4];
for (int i = 0; i < bin.length() / 4; i++) {
hexString[i] = "";
for (int j = index; j < index + 4; j++) {
hexString[i] += bin.charAt(j);
}
index += 4;
}
for (int i = 0; i < bin.length() / 4; i++) {
System.out.print(hexString[i] + " ");
}
System.out.println("\n" + bin.length());
String[] result = binaryToHex(hexString);
for (int i = 0; i < result.length; i++) {
System.out.print("" + result[i].toUpperCase());
}
System.out.println("");
}
public static String[] binaryToHex(String[] bin) {
String[] result = new String[bin.length];
for (int i = 0; i < bin.length; i++) {
result[i] = Integer.toHexString(Integer.parseInt(bin[i], 2));
}
//return Integer.toHexString(Integer.parseInt(bin[0], 2));
return result;
}
}
}
回答by Benvorth
Use this for any binary string length:
将此用于任何二进制字符串长度:
String hexString = new BigInteger(binaryString, 2).toString(16);
回答by sibel bayirli
private final String[] hexValues = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
private final String[] hexValues = {"0","1","2","3","4","5","6","7","8","9","A ","B","C","D","E","F"};
public void binaryToHexadecimal(String binary){
String hexadecimal;
binary = leftPad(binary);
System.out.println(convertBinaryToHexadecimal(binary));
}
public String convertBinaryToHexadecimal(String binary){
String hexadecimal = "";
int sum = 0;
int exp = 0;
for (int i=0; i<binary.length(); i++){
exp = 3 - i%4;
if((i%4)==3){
sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
hexadecimal = hexadecimal + hexValues[sum];
sum = 0;
}
else
{
sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp));
}
}
return hexadecimal;
}
public String leftPad(String binary){
int paddingCount = 0;
if ((binary.length()%4)>0)
paddingCount = 4-binary.length()%4;
while(paddingCount>0) {
binary = "0" + binary;
paddingCount--;
}
return binary;
}