java如何把int,按4位一取,转换成16进制输出?

goshiter 2012-12-19 10:40:48
问题还可以变一下:
byte[] b={12,14,15,16};
把b连成一个32位的;
然后按4位一取,换成16进制,输出?
...全文
866 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
youngplayee 2012-12-20
  • 打赏
  • 举报
回复
int convertBytesToInt(byte[] b) { if(b == null || b.length != 4) return 0; int n0 = (b[3]&0xff)<<24; int n1 = (b[2]&0xff)<<16; int n2 = (b[1]&0xff)<<8; int n3 = (b[0]&0xff); return n0|n1|n2|n3; }
youngplayee 2012-12-20
  • 打赏
  • 举报
回复
补充一下,由于java里面没有unsigned byte,所以需要通过&0xff将符号位去掉。 int convertBytesToInt(byte[] b) { if(b == null || b.length != 4) return 0; int n0 = b[3]; n0= (n0&0xff)<<24; int n1 = b[2]; n1= (n1&0xff)<<16; int n2 = b[1]; n2= (n2&0xff)<<8; int n3 = b[0]; n3= (n3&0xff)<<24; return n0|n1|n2|n3; }
youngplayee 2012-12-20
  • 打赏
  • 举报
回复
一般int变成byte数组是反的。高位在后,低位在前。 byte[] b={12,14,15,16}; int convertBytesToInt(byte[] b) { return (b[3]<<24)|(b[2]<<16)|(b[1]<<8)|b[0]; }
IT人.阿标 2012-12-19
  • 打赏
  • 举报
回复
public class ByteTran {
	static byte[] b={12,14,15,16};
	
	public static void main(String[] args){
		Integer resut = 0;
		for(int i = 0; i < b.length; i++){
			resut |= (b[i]<<((b.length-i-1)*8));
		}
		//输出十六进制
		System.out.println(Integer.toHexString(resut));
	}
}

80,359

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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