The description provided in the Java doc for the method is:
Returns the value of this Integer as a byte.
It is obvious that one byte can only represent upto a value of 255. If the value contained is larger than 255, there would be a loss of data.
My question is why the Java API developers did not provide something like a byte array rather than a byte as the return type. Am I missing someting here? [ October 31, 2006: Message edited by: Isuru Sampath ]
But Bauke, your code does something entirely different from what Isuru's code does.
Bauke's code converts the int to a string of characters (text), and then converts the string in to an array of bytes that represent the digits in whatever character encoding is the default on the platform you run it on. Suppose the encoding is ASCII or UTF-8, an int with the value 342876 would be converted to a byte array of 6 bytes: 51, 52, 50, 56, 55, 54
What Isuru means is that he wants the 32 bits of the int converted into 4 bytes: 0, 5, 59, 92 (in big-endian order).
Isuru: OK, the code with the ByteArrayOutputStream works but it seems a bit overkill to me. You could just do some bit manipulations:
That's faster, doesn't involve creating ByteArrayOutputStream and DataOutputStream objects, and also avoids the need for users of the method to deal with the IOException.
Nifty ha? [ October 31, 2006: Message edited by: Jesper Young ]
Originally posted by Bauke Scholtz: Where can I read this?
That's what the code he posted above with the ByteArrayOutputStream and DataOutputStream does.
Joined: Jun 26, 2003
Very many thanks to Jesper and Bauke.
Yes Jesper, what I wanted was the binary representation of the int in Big Endean order. And the code snippet you provided is really nifty and guess it is really fast since bit shifting is the fastest operations we can get (my belief :roll: ).
But the reason I like the previous code is that it does not have to have the byte array length hard coded. It will create a byte array to hold the input integer whatever it's size. I 100% agree with you that it is kind of overkill if the integer size is limited or known. On the other hand if the integer size is dynamic, the previous code snippet is ideal. Guess the choice should be based on the requirement.
In Java, an int is always 32 bits, doesn't matter what system you're running it on. Even if you're running it on a 16-bit or 64-bit processor or operating system, and int is 32 bits (unlike C/C++, where the size of an int is system-dependent).
So writing code that's independent of the size of an int is irrelevant in Java...