Reprinted please indicate the source!
Link: http://blog.csdn.net/zgyulongfei/article/details/7738970
During the project, all the int and long values need to be converted to byte when sending network streams according to the protocol. Therefore, the following conversion method is written, hoping to help friends who need it ^_^
If you have less time to talk about it, you can directly access the code.
public class Utilities {public static byte[] int2Bytes(int num) {byte[] byteNum = new byte[4];for (int ix = 0; ix < 4; ++ix) {int offset = 32 - (ix + 1) * 8;byteNum[ix] = (byte) ((num >> offset) & 0xff);}return byteNum;}public static int bytes2Int(byte[] byteNum) {int num = 0;for (int ix = 0; ix < 4; ++ix) {num <<= 8;num |= (byteNum[ix] & 0xff);}return num;}public static byte int2OneByte(int num) {return (byte) (num & 0x000000ff);}public static int oneByte2Int(byte byteNum) {
// Intreturn bytenum> 0? Bytenum: (128 + (128 + bytenum);} public static byte [] long2bytes (long num) {byte [] bytenum = new byte [8]; for (int ix = 0; ix <8; ++ IX) {int offset = 64-(IX + 1) * 8; bytenum [ix] = (byte) (Num> offset) & 0xff);} return bytenum;} public static long bytes2long (byte [] bytenum) {long num = 0; For (int ix = 0; IX <8; ++ IX) {num <= 8; num | = (bytenum [ix] & 0xff) ;}return num ;}}
Public class testmain {public static void main (string [] ARGs) {int num = 129; system. out. println ("test int value:" + num); byte [] int2bytes = utilities. int2bytes (Num); system. out. printf ("int to Bytes:"); For (INT I = 0; I <4; ++ I) {system. out. print (int2bytes [I] + "");} system. out. println (); int bytes2int = utilities. bytes2int (int2bytes); system. out. println ("bytes to int:" + bytes2int); byte int2onebyte = utilities. int2onebyte (Num); system. out. println ("int to one byte:" + int2onebyte); int onebyte2int = utilities. onebyte2int (int2onebyte); system. out. println ("one byte to int:" + onebyte2int); system. out. println (); long longnum= 100000; system. out. println ("the long value of the test is:" + longnum); byte [] long2bytes = utilities. long2bytes (longnum); system. out. printf ("long to Bytes:"); For (int ix = 0; ix <long2bytes. length; ++ IX) {system. out. print (long2bytes [ix] + "");} system. out. println (); long bytes2long = utilities. bytes2long (long2bytes); system. out. println ("bytes to long:" + bytes2long );}}
The test results are as follows:
The Int value in the test is: 156int to Bytes: 0 0-100 bytes to int: 156int to one byte:-100one byte to int: 156. The long value in the test is: 100000long to Bytes: 0 0 0 0 1-122-96 bytes to long: 100000