Java Hex Calculate toHex(byte b)

Here you can find the source of toHex(byte b)

Description

convert to hex string

License

Open Source License

Parameter

Parameter Description
b The item to convert to hex

Return

The hex string

Declaration

public static String toHex(byte b) 

Method Source Code

//package com.java2s;
/*// w  ww  .  j a  v  a2  s . c o m
 * Copyright 2011, United States Geological Survey or
 * third-party contributors as indicated by the @author tags.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/  >.
 *
 */

public class Main {
    /** convert to hex string
     *@param b The item to convert to hex 
     *@return The hex string */
    public static String toHex(byte b) {
        return toHex(((long) b) & 0xFFL);
    }

    /** convert to hex string
     *@param b The item to convert to hex 
     *@return The hex string */
    public static String toHex(short b) {
        return toHex(((long) b) & 0xFFFFL);
    }

    /** convert to hex string
     *@param b The item to convert to hex 
     *@return The hex string */
    public static String toHex(int b) {
        return toHex(((long) b) & 0xFFFFFFFFL);
    }

    /** convert to hex string
     *@param i The item to convert to hex 
     *@return The hex string */
    public static String toHex(long i) {
        StringBuilder s = new StringBuilder(16);
        int j = 60;
        int k;
        long val;
        char c;
        boolean flag = false;
        s.append("0x");

        for (k = 0; k < 16; k++) {
            val = (i >> j) & 0xf;
            //prt(i+" i >> j="+j+" 0xF="+val);
            if (val < 10)
                c = (char) (val + '0');
            else
                c = (char) (val - 10 + 'a');
            if (c != '0')
                flag = true;
            if (flag)
                s.append(c);
            j = j - 4;
        }
        if (!flag)
            s.append("0");
        return s.toString();
    }
}

Related

  1. toHex(byte b)
  2. toHex(byte b)
  3. toHex(byte b)
  4. toHex(byte b)
  5. toHex(byte b)
  6. toHex(byte b)
  7. toHex(byte b, char[] charArray, int from)
  8. toHex(byte b, String prefix)
  9. toHex(byte bytes[])