Converting binary string to a hexadecimal string JAVA

前端 未结 7 867
陌清茗
陌清茗 2020-12-16 14:32

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:

相关标签:
7条回答
  • 2020-12-16 15:23

    /* * 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 {

    /**
     * @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;
    }
    

    }

    0 讨论(0)
提交回复
热议问题