博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基本类型数据转换(int,char,byte)
阅读量:6038 次
发布时间:2019-06-20

本文共 2357 字,大约阅读时间需要 7 分钟。

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();        }    }}

 

转载于:https://www.cnblogs.com/suiyueqiannian/p/6961070.html

你可能感兴趣的文章
关于Tomcat配置相关总结
查看>>
安装PDO_MYSQL遇到的问题:error: Cannot find MySQL header files under
查看>>
CocoaPods最新安装及跳过pod setup快速安装教程
查看>>
必须用C模拟OS?
查看>>
JavaScript引入
查看>>
ARM9代码分析启动MAIN.C
查看>>
JSON
查看>>
4.3 Verilog练习(2)
查看>>
浅谈html5某些新元素的用途
查看>>
csv文件的操作
查看>>
搭建ssm框架项目基本原理和主要的配置文件小结
查看>>
导出表结构sql语句
查看>>
centOS7服务管理与启动流程
查看>>
Unity2018.1中文更新日志速览版
查看>>
WPF 4 日历控件(Calendar)
查看>>
树莓派之OLED12864视频播放—BadApple
查看>>
论如何优雅地拿下PHPCMS
查看>>
[PHP] 数据结构-二叉树的创建PHP实现
查看>>
让你的Blend“编辑其他模板”菜单里出现你的Style
查看>>
UILabel添加图片之富文本的简单应用
查看>>