How do I convert an integer to unsigned 32 bit big endian byte array

社会主义新天地 提交于 2019-12-25 04:43:32

问题


I have an integer which represents a frame length. I would like to know how I can convert the integer to an unsigned 32 bit (4 bytes) big endian byte array in Java


回答1:


A big endian byte sequence is simply 'big numbers first'. But of course, converted into binary. So it's shockingly easy with almost any 'hex' conversion - that's the default output.

It depends rather which language you're intending to use, but sprintf is pretty common. The format string to do this is %X so in perl you'd have something like:

my $big_endian = sprintf ( "%X", 61613 ); 
print $big_endian;

little endian is more complex - it's reversing each byte (or pair of hex values).

Of course, specifics of what you're trying to accomplish depend rather more on which language you're working in - which you've neither specified, nor offered example code of what you've got so far.




回答2:


In Java, integer is signed and big endian. Singed number are encoded in two's complement format. To convert a two's complement number to unsigned number, just follow the following rules:

If you want a unsigned representation, just following the rules to get the unsigned number. As the integer already in big endian, just split the result in 4 bytes.



来源:https://stackoverflow.com/questions/28099559/how-do-i-convert-an-integer-to-unsigned-32-bit-big-endian-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!