数字如何转成byte2字节

findshine 2016-11-16 07:19:21
数字如何转成byte2字节,又如何转回来?
...全文
412 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_30169767 2016-11-17
  • 打赏
  • 举报
回复
/** * 短整数转字节数组 * @param s type of short 要转换的short值 * @return byte[] 数组 */ public static byte[] short2bytes(short s) { byte[] bytes = new byte[2]; for (int i = 1; i >= 0; i--) { bytes[i] = (byte)(s % 256); s >>= 8; } return bytes; } /** * 字节数组转短整数 * @param bytes * @return short */ public static short bytes2short(byte[] bytes) { short s = (short)(bytes[1] & 0xFF); s |= (bytes[0] << 8) & 0xFF00; return s; } /** * 整数转字节数组 * @param value type of int 要转换的int值 * @return byte[] 数组 */ public static byte[] intToBytes(int value) { byte[] bytes = new byte[4]; bytes[3] = (byte) ((value>>24) & 0xFF); bytes[2] = (byte) ((value>>16) & 0xFF); bytes[1] = (byte) ((value>>8) & 0xFF); bytes[0] = (byte) (value & 0xFF); return bytes; } /** * 字节数组转整数 * @param src byte数组 * @param offset 从数组的第offset位开始 * @return int数值 */ public static int bytesToInt(byte[] bytes, int offset) { int value; value = (int) ((bytes[offset] & 0xFF) | ((bytes[offset+1] & 0xFF)<<8) | ((bytes[offset+2] & 0xFF)<<16) | ((bytes[offset+3] & 0xFF)<<24)); return value; }

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧