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.