2025年3月19日 星期三 甲辰(龙)年 月十八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Java

java int转byte数组

时间:06-29来源:作者:点击数:22

各种基本数据类型转byte数组并反转


int 转 byte[]   低字节在前(低字节序)

  • public static byte[] toLH(int n) {
  • byte[] b = new byte[4];
  • b[0] = (byte) (n & 0xff);
  • b[1] = (byte) (n >> 8 & 0xff);
  • b[2] = (byte) (n >> 16 & 0xff);
  • b[3] = (byte) (n >> 24 & 0xff);
  • return b;
  • }

int 转 byte[]   高字节在前(高字节序)

  • public static byte[] toHH(int n) {
  • byte[] b = new byte[4];
  • b[3] = (byte) (n & 0xff);
  • b[2] = (byte) (n >> 8 & 0xff);
  • b[1] = (byte) (n >> 16 & 0xff);
  • b[0] = (byte) (n >> 24 & 0xff);
  • return b;
  • }

byte[] 转 int 低字节在前(低字节序)

  • public int toInt(byte[] b){
  • int res = 0;
  • for(int i=0;i<b.length;i++){
  • res += (b[i] & 0xff) << (i*8);
  • }
  • return res;
  • }

byte[] 转 int 高字节在前(高字节序)

  • public static int toInt(byte[] b){
  • int res = 0;
  • for(int i=0;i<b.length;i++){
  • res += (b[i] & 0xff) << ((3-i)*8);
  • }
  • return res;
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门