基本类型数据转换(int,char,byte)

Posted 岁月千年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基本类型数据转换(int,char,byte)相关的知识,希望对你有一定的参考价值。

public class DataUtil {

    public static void main(String[] args) {
        int a = 8;
        int value = charToInt(byteToChar(intToByte(a)));
        int value2 = byteToInt(charToByte(intTochar(a)));
        System.out.println(value);
        System.out.println(value2);
    }

    public static byte[] intToByte(int value){
        byte[] b = new byte[4];
        b[0] = (byte) (value & 0xff);
        b[1] = (byte) ((value >> 8) & 0xff);
        b[2] = (byte) ((value >> 16) & 0xff);
        b[3] = (byte) ((value >> 24) & 0xff);
        return b;
    }

    public static int byteToInt(byte[] bytes){
        return  (bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8)
                | ((bytes[2] & 0xff) << 16) | ((bytes[3] & 0xff) << 24);
    }

    public static char[] intTochar(int value){
        char[] c = new char[2];
        c[0] = (char) (value & 0xffff);
        c[1] = (char) ((value >> 16) & 0xffff);
        return c;
    }

    public static int charToInt(char[] chars){
        return (chars[0] & 0xffff) | ((chars[1] & 0xffff) << 16);
    }

    public static char[] byteToChar(byte[] bytes){
        char[] v = new char[2];
        v[0] = (char) ((bytes[0] & 0xffff) | ((bytes[1] & 0xffff) << 8));
        v[1] = (char) ((bytes[2] & 0xffff) | ((bytes[3] & 0xffff) << 8));
        return v;
    }

    public static byte[] charToByte(char[] chars){
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (chars[0] & 0xff);
        bytes[1] = (byte) ((chars[0] >> 8) & 0xff);
        bytes[2] = (byte) (chars[1] & 0xff);
        bytes[3] = (byte) ((chars[1] >> 8) & 0xff);
        return bytes;
    }

    public static byte[] objectToBytes(Object object) throws IOException{
        try(ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream outputStream = new ObjectOutputStream(arrayOutputStream)){
            outputStream.writeObject(object);
            outputStream.flush();
            return arrayOutputStream.toByteArray();
        }
    }

    public static Object bytesToObject(byte[] bytes) throws IOException,ClassNotFoundException{
        try (ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(arrayInputStream)){
            return objectInputStream.readObject();
        }
    }
}

 

以上是关于基本类型数据转换(int,char,byte)的主要内容,如果未能解决你的问题,请参考以下文章

Java中 String与基本数据类型,包装类,char[],byte[]之间的转换

Java数据类型自动转换的优先顺序

c#怎么把byte转化成int

Java数据类型

byte和int,char类型有啥区别

C语言中各种数据类型有啥区别?