This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
naresh voota wrote:putting long in int will reduce the precision of the value stored.
long l = 9;
String s= Long.toString(l);
byte b = s.getBytes();
once you pass this byte array over network,
String s = new String(b);
Long l = Long.valueOf(s);
hopefully this will help. Thanks.
That works for values less than 10,000. Once you get to 10,000 you need 5 bytes to hold the String, so, you loose even more than you do when you convert to int. Oh, and any value less than 1,000 would take 3 or fewer bytes, so then you would have to test if < 1000, pad byte array, else if > 9999, throw bytes away.
No, if you look at the code Steve is referring to, one byte ends up representing one character in a String representation. So the largest number that can be represented this way is 9999, at four digits. Of course this isn't a very good way to try to fit a long into 4 bytes. Simply casting to int would be easier, and covers a wiser range of possible values.
Steve Luke wrote:
That works for values less than 10,000.
Correction: less than Integer.MAX_VALUE.
One byte is 8 bits, you know.
That is true for the answers suggesting to use a cast to int. Naresh, whom I was responding to, suggested converting the long to a String, then the String to byte. When you do this and have more than 4 characters (digits) you get more than 4 bytes. See:
Length of byte for 10000 is: 5
Santoshkumar Jeevan Pawar
Joined: Aug 19, 2006
Here we lose the actual value,please check below code when we typecast from long to int.
long l = new Date().getTime(); //1238583275781
int i = (int)myLong; // value becomes 1633321080
Santoshkumar Jeevan Pawar wrote:But at the same time i dont want to lose actual value......
Then you have no choice but to increase your array size to 8. A long simply requires 64 bits (= 8 bytes), nothing more and nothing less. By trying to squeeze it into an int you lose information. You can also convert the long to a float (4 bytes), but then you lose precision on the lower end:
So the only way to keep your actual value is: make sure you send the actual complete long.