代码,最能说明问题:
AllByte.java
package com.bytes; /** * int,short,String与byte互相转换 * */ public class AllByte { /** * 1 int 转换成 4 bytes * * @param data * @return */ public static byte[] int2byte(int data) { byte[] buf = new byte[4]; buf[0] = (byte) ((data >> 24) & 0xff); buf[1] = (byte) ((data >> 16) & 0xff); buf[2] = (byte) ((data >> 8) & 0xff); buf[3] = (byte) (data & 0xff); return buf; } /** * 4 bytes 转换成 1 int * * @param data * @return */ public static int byte2int(byte[] data) { if (data == null || data.length != 4) { return 0; } return ((data[0] & 0x000000ff) << 24) | ((data[1] & 0x000000ff) << 16) | ((data[2] & 0x000000ff) << 8) | (data[3] & 0x000000ff); } /** * 2 bytes 转换成 1 short * * @param data * @return */ public static short byte2short(byte[] data) { if (data == null || data.length != 2) { return 0; } return (short) ((data[0] & 0x00FF) << 8 | data[1] & 0x00ff); } /** * 1 short 转换成 2 bytes * * @param data * :需要转换的short * @return */ public static byte[] short2byte(short data) { byte[] buf = new byte[2]; buf[0] = (byte) ((data >> 8) & 0xff); buf[1] = (byte) (data & 0xff); return buf; } /** * * @param str * :需要转换的字符串 * @param encode * :转换的编码 * @return:结果 */ public static byte[] string2byte(String str, String encode) { try { return str.getBytes(encode); } catch (Exception e) { return null; } } /** * * @param str * :需要转换的字节数组 * @param encode * :转换的编码 * @return:结果 */ public static String byte2string(byte[] b, String encode) { try { return new String(b, encode); } catch (Exception e) { return null; } } }
Java字节流互转示例代码
本文提供了一个Java程序示例,展示了如何将int、short、String和byte进行互相转换,包括从int到byte数组的转换,从byte数组到int的转换,从short到byte数组的转换,以及从byte数组到short的转换。
222

被折叠的 条评论
为什么被折叠?



