int,short,String与byte互相转换

Java字节流互转示例代码
本文提供了一个Java程序示例,展示了如何将int、short、String和byte进行互相转换,包括从int到byte数组的转换,从byte数组到int的转换,从short到byte数组的转换,以及从byte数组到short的转换。

代码,最能说明问题:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值