首页 > 编程语言 > 详细

Java中转换为十六进制的几种实现

时间:2018-08-12 17:57:38      阅读:157      评论:0      收藏:0      [点我收藏+]
public class HexUtil {

    private static final String[] DIGITS_UPPER =
            {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

    public static void main(String[] args) throws DecoderException {

        System.out.println(toHex1((byte) -128));
        System.out.println(toHex2((byte) -128));
        System.out.println(toHex3((byte) -128));
        System.out.println(toHex4((byte) -128));
    }


    public static String toHex1(byte value) {
        int high = (value & 0xF0) >>> 4;
        int low = value & 0x0F;
        return DIGITS_UPPER[high] + DIGITS_UPPER[low];
    }

    public static String toHex2(byte value) {
        int high = (value >>> 4) & 0x0F;
        int low = value & 0x0F;
        return DIGITS_UPPER[high] + DIGITS_UPPER[low];
    }


    public static String toHex3(byte value) {
        int tmp = value;
        if (value < 0) {
            tmp = value + 256;
        }
        int high = tmp / 16;
        int low = tmp % 16;
        return DIGITS_UPPER[high] + DIGITS_UPPER[low];
    }

    public static String toHex4(byte value) {
        return String.format("%x", value);
    }

}
参考

补码

Java中转换为十六进制的几种实现

原文:https://www.cnblogs.com/lxyit/p/9463586.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!