Java Binary to Hex binaryToHex(char[] binaryStr)

Here you can find the source of binaryToHex(char[] binaryStr)

Description

binary To Hex

License

Apache License

Declaration

private static char[] binaryToHex(char[] binaryStr) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {

    private static char[] binaryToHex(char[] binaryStr) {
        return binaryToChar(binaryStr, 4);
    }// w  ww .j  a v a2  s  .c  om

    private static char[] binaryToChar(char[] binaryStr, int charLen) {
        int len = binaryStr.length;
        int num = 0;
        if (len % charLen == 0)
            num = len / charLen;
        else
            num = len / charLen + 1;

        char[] values = new char[num];

        int end = len - 1;
        for (int pos = num - 1; pos >= 0; pos--) {
            values[pos] = getCharDigit(binaryStr,
                    end - charLen + 1 >= 0 ? end - charLen + 1 : 0, end);
            end -= charLen;
        }
        return values;
    }

    private static char getCharDigit(char[] binaryStr, int start, int end) {
        int sum = 0;
        int multiplier = 1;
        for (int index = end; index >= start; index--) {
            if (binaryStr[index] == '1')
                sum += multiplier;
            multiplier *= 2;
        }
        if (sum < 10)
            return (char) ('0' + sum);
        else
            return (char) ('a' + sum - 10);
    }
}

Related

  1. bin2hex(String str)
  2. binaryString2hexString(String bString)
  3. binaryToHex(byte[] ba)
  4. binaryToHex(byte[] bytes)
  5. binaryToHex(byte[] data)
  6. binaryToHex(int binary)
  7. BinaryToHexString(byte[] bytes)
  8. binaryToHexString(String binaryValue)
  9. binToHex(byte[] bin)