首页 > 代码库 > 基本类型数据转换(int,char,byte)
基本类型数据转换(int,char,byte)
public class DataUtil { public static void main(String[] args) { int a = 8; int value =http://www.mamicode.com/ 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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。