六号线晚报0524

天气:晴 风力:无风

java十六进制转各种形式

public class Decoder {
    public static void main(String[] args) {


        //十进制形式
        int anInt1 = 123_45_6;
        //二进制、十六进制等形式也支持
        int anInt2 = 0b10_0110_100;
        int anInt3 = 0xFF_EC_DE_5E;
        //小数形式也支持
        float pi = 3.14_15F;
        double aDouble = 3.14_15;
        //多个下划线相连
        int chain = 5______2____0;

        int i = 0xFFFFFFFF;

        System.out.println(i); //-1

        //        byte b = 0xFF;   错误byte-128~127
        byte b = (byte) 0xFF;
        System.out.println(b);  //-1

        Double d = 2.1353;
        byte b1 = d.byteValue();
        System.out.println(b1);  //2

        byte[] bytes = {0x61, 0x62};

        String s1 = new String(bytes);
        System.out.println(s1);  //ab


        String unicodeStr = "\\u73\\u74\\u72\\u69\\u6e\\u67\\u4e2d\\u6587\\u6c49\\u5b57";
        System.out.println(unicode2String(unicodeStr));

        String str = "string中文汉字";
        System.out.println(string2Unicode(str));

        //unicode字符串和字符串转化实际是char和int的转化
        int ui = 0x4e2d;
        System.out.println((char) ui);  //中
        char ci = '中';
        System.out.println(Integer.toHexString(ci)); //4e2d


        //小数和16进制字符串转化
        float f = 666663.123477777f; //必须加f,要不会认为d
        System.out.println(Integer.toHexString(Float.floatToIntBits(f))); //4922c272
        String hexF = "4922c272";
        System.out.println(Integer.parseInt(hexF, 16)); //1227014770
        System.out.println(Float.intBitsToFloat(Integer.parseInt(hexF, 16)));//666663.1 在转int时丢失精度尽量保留高位

        double d1 = 3.123488888d; //是否加d没有影响结果
        System.out.println(Long.toHexString(Double.doubleToLongBits(d1))); //4008fce7bdfb0906
        String hexD = "4008fce7bdfb0906";
        System.out.println(Double.longBitsToDouble(Long.parseLong(hexD, 16)));


        System.out.println(Integer.MAX_VALUE);

    }

    public static String unicode2String(String unicodeStr) {
        StringBuffer sb = new StringBuffer();
        String[] hexStr = unicodeStr.split("\\\\u");
        for (int i = 1; i < hexStr.length; i++) {  //第一个是空格
            int data = Integer.parseInt(hexStr[i], 16); //unicode英文数字1个字节中文2个字节,int四个字节可以容纳
            System.out.println(data);
            sb.append((char) data);  //java char两个字节,中英文都可容纳

        }
        return sb.toString();
    }

    public static String string2Unicode(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            System.out.println(ch);
            sb.append("\\u" + Integer.toHexString(ch));
        }
        return sb.toString();
    }
}

你可能感兴趣的:(六号线晚报0524)