27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

String, text, numbers, I/O I part<br />

How do I encode the value of a variable of type long (or int) into bytes? And how<br />

do I restore the original value of the long (or int) variable back<br />

How do I encode the value of a variable of type long (or int) into bytes such that the<br />

number of bytes used will always be the same, say 4 bytes?<br />

Answer:<br />

int in; ...<br />

byte b1 = (byte)(in & 0xff);<br />

byte b2 = (byte)((in >> 8) & 0xff);<br />

byte b3 = (byte)((in >> 16) & 0xff);<br />

byte b4 = (byte)(in >>> 24);<br />

: How do I restore the original value of the long (or int) variable back<br />

: from the bytes that i have just created then?<br />

Answer:<br />

int in = (b1 & 0xff) | ((b2 > 8) | (b4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!