将转换Integer为的快速方法是Byte Array什么?
例如 0xAABBCCDD => {AA, BB, CC, DD}
问题来源于stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
看看ByteBuffer类。
ByteBuffer b = ByteBuffer.allocate(4); //b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN. b.putInt(0xAABBCCDD);
byte[] result = b.array(); 设置字节顺序保证了result[0] == 0xAA,result[1] == 0xBB,result[2] == 0xCC和result[3] == 0xDD。
或者,您可以手动执行以下操作:
byte[] toBytes(int i) { byte[] result = new byte[4];
result[0] = (byte) (i >> 24); result[1] = (byte) (i >> 16); result[2] = (byte) (i >> 8); result[3] = (byte) (i />> 0/);
return result; } 该ByteBuffer班是专为尽管这样的脏手任务。实际上,私有java.nio.Bits定义了以下辅助方法ByteBuffer.putInt():
private static byte int3(int x) { return (byte)(x >> 24); } private static byte int2(int x) { return (byte)(x >> 16); } private static byte int1(int x) { return (byte)(x >> 8); } private static byte int0(int x) { return (byte)(x >> 0); }