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

时间:2023-03-08 20:33:54
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();
}
}
}