Java byte order (byte sequence conversion for network data transfer in different languages) __java

Source: Internet
Author: User

Big-endian (large byte sequence, high byte order)
Little-endian (small byte order, low byte order)
Host byte order
Network byte order
Java byte order

1. Big-endian, Little-endian are related to multibyte-type data such as the Int,short,long type, but have no effect on single-byte byte data. Big-endian is low byte emissions at the low end of memory, high byte emissions in the high-end memory. and Little-endian just the opposite.
like int a = 0x05060708
stored in the case of Big-endian:
BYTE number 0 1 2 3
Data 05 06 07 08
stored in the case of Little-endian:
BYTE number 0 1 2 3
Data 08 07 06 05

2. Big-endian, Little-endian, and CPU-related, each CPU is not Big-endian is Little-endian,. The IA architecture is Little-endian on the CPU and PowerPC, SPARC, and Motorola processors. This is actually called the host byte order. and the network byte order is refers to the data on the network transmission is the big head or the small end, the network byte order in the Internet is Big-endian. The so-called Java byte order refers to the order in which multibyte types of data are stored in Java virtual machines, and the Java byte order is Big-endian.

3. So when you write the communication program with C + +, you must use HTONL and htons to convert the integer and short integer data from the host byte sequence to the network byte sequence before sending the data, After receiving data for integer and short integer data, you must call Ntohl and Ntohs to implement the conversion from network byte order to host byte order. If one side of the communication is a Java program, one side is C/s + + program, you need to use the above methods on the C + + side of the byte-order conversion, while the Java side, you do not need to do any processing, because Java byte order and network byte sequence are Big-endian, as long as One side can be correctly converted (before sending from the host to the network sequence, receive the reverse transformation). If both sides of the communication are Java, there is no need to consider the problem of byte ordering at all.

4. If there is no problem with all the Powerpc,sparc and Motorola CPU hosts on the network, there is often a data transfer error due to the fact that there are a large number of IA architecture CPUs.

5. The problem raised at the beginning of the article is that because the program runs on the PC server of the X86 architecture, the one end of the sending data is implemented in C, and the receiver is implemented in Java, while the sender does not convert from the host byte sequence to the network byte sequence before sending the data. In this way the receiving end receives the Little-endian data, and the data explains the natural error.
The specific data is as follows, the actual data sent is 23578
Send data: 1 a 5C
When the receiver receives the data, it interprets the specific data by Big-endian. You're going to figure it out and compare it.


===============================================================================================

Big endian and Little endian

When it comes to the question of byte-order, it inevitably involves two big CPU factions. That's Motorola's PowerPC series CPU and Intel's x86 series CPU. The PowerPC series uses the big endian method to store data, while the x86 series uses little endian to store the data. So what is big endian and what is little endian?

In fact, the big endian refers to low address storage of the highest effective byte (MSB), while the little endian is low address storage of the lowest effective byte (LSB), that is often said low first, high in the rear.
The text description may be more abstract, described below with an image. For example, the order in which digital 0x12345678 are stored in two different byte-sequence CPUs is as follows:

Big endian

Low address High address
----------------------------------------->
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      12 |     34 |     56 | 78 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Little endian

Low address High address
----------------------------------------->
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      78 |     56 |     34 | 12 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

From the above two figure can be seen, the use of big endian way to store data is in line with our human thinking habits. And little endian,!@#$%^&*, go to Hell-_-| | |

Why pay attention to the problem of byte order? You might ask that. Of course, if you write a program that runs only under a stand-alone environment and does not deal with other people's programs, you can completely ignore the existence of the byte sequence. But what if your program has to interact with someone else's program? Especially when you apply the results of your calculations on a computer to a group of computers. I want to speak two languages here. The data stored order in the C + + language program is related to the CPU where the compiled platform resides, while the Java program is the only one that uses the big endian method to store the data. Imagine what it would be like to communicate with someone else's Java program if you were writing a program under the x86 platform. Take the above 0x12345678 for example, your program passed to someone else's data, will point to 0x12345678 Pointer to the Java program, because Java takes the big endian way to store data, it is natural that it will translate your data to 0x78563412. What the. Turned into a different number. Yes, that's the consequence. Therefore, it is necessary to do byte-order conversion before your C program is passed to the Java program.

Coincidentally, all network protocols are also using a big endian way to transmit data. So sometimes we're going toBig endian way called network byte order。 When two hosts with different byte orders communicate, the data must be converted into the network byte sequence before transmitting. The ANSI C provides four macros that convert bytes.


 

/** * Communication Format Conversion * * Java and some Windows programming languages such as C, C + +, Delphi written by the network program to communicate, the need for the corresponding conversion * high, low byte conversion * Windows byte order is low byte start * Linux,unix byte order is High-byte start * Java is a high byte beginning regardless of platform change/public class Formattransfer {/** * converts int to low byte in front, high byte array * @param n int * @re
  Turn byte[] */public static byte[] Tolh (int n) {byte[] b = new Byte[4];
  B[0] = (byte) (n & 0xff);
  B[1] = (byte) (n >> 8 & 0xff);
  B[2] = (byte) (n >> & 0xff);
  B[3] = (byte) (n >> & 0xff);
return b; /** * converts int to high byte before, byte array after low BYTE * @param n int * @return byte[] * * public static byte[] Tohh (int n) {byte[]
  b = new Byte[4];
  B[3] = (byte) (n & 0xff);
  B[2] = (byte) (n >> 8 & 0xff);
  B[1] = (byte) (n >> & 0xff);
  B[0] = (byte) (n >> & 0xff);
return b; /** * Convert short to low byte before, byte array after high Byte * @param n Short * @return byte[]/public static byte[] Tolh (short n) {b
  Yte[] B = new byte[2];
  B[0] = (byte) (n & 0xff); B[1] = (byte) (n >> 8 & 0xff);
return b; /** * Converts short to high byte before, byte array after low byte * @param n Short * @return byte[]/public static byte[] Tohh (short n) {b
  Yte[] B = new byte[2];
  B[1] = (byte) (n & 0xff);
  B[0] = (byte) (n >> 8 & 0xff);
return b;
  /** * Convert int to high byte before, low byte array public static byte[] Tohh (int number) {int temp = number;
  Byte[] B = new Byte[4];
    for (int i = b.length-1 i > 1; i--) {b = new Integer (temp & 0xff). Bytevalue ();
  temp = temp >> 8;
return b;
    public static byte[] Inttobytearray (int i) {byte[] abyte0 = new Byte[4];
    ABYTE0[3] = (byte) (0xFF & i);
    ABYTE0[2] = (byte) ((0xff00 & i) >> 8);
    ABYTE0[1] = (byte) ((0xff0000 & i) >> 16);
    Abyte0[0] = (byte) ((0xff000000 & i) >> 24);
return abyte0; * * */** * converts float to low byte before, byte array after high BYTE */public static byte[] Tolh (float f) {return Tolh FLOAT.FLOATTORAWINTBI
TS (f)); }/** * Will FloAt is converted to high byte before, byte array after low byte/public static byte[] Tohh (float f) {return tohh (Float.floattorawintbits (f));} /** * Converts a string to a byte array/public static byte[] Stringtobytes (string s, int length) {while s.getbytes (). Length <
  Length) {s + = "";
return S.getbytes (); /** * Converts a byte array to a string * @param b byte[] * @return string/public static string bytestostring (byte[] b) {S
  Tringbuffer result = new StringBuffer ("");
  int length = B.length;
  for (int i=0; i<length; i++) {result.append ((char) (b & 0xFF));
return result.tostring (); /** * Converts a string to a byte array * @param s String * @return byte[] */public static byte[] Stringtobytes (string s) {RET
Urn S.getbytes ();
  /** * Converts a high byte array to an int * @param b byte[] * @return int/public static int hbytestoint (byte[] b) {int s = 0;
    for (int i = 0; i < 3; i++) {if (b >= 0) {s = s + b;
    else {s = s + 256 + b;
  } s = S * 256;
 } if (B[3] >= 0) {   s = s + b[3];
  else {s = s + 256 + b[3];
return s;
  /** * Converts a low byte array to an int * @param b byte[] * @return int/public static int lbytestoint (byte[] b) {int s = 0;
    for (int i = 0; i < 3; i++) {if (B[3-i] >= 0) {s = s + b[3-i];
    else {s = s + 256 + b[3-i];
  } s = S * 256;
  } if (B[0] >= 0) {s = s + b[0];
  else {s = s + 256 + b[0];
return s;  /** * High byte array to short conversion * @param b byte[] * @return Short */public static short Hbytestoshort (byte[] b) {int
  s = 0;
    if (B[0] >= 0) {s = s + b[0];
    else {s = s + 256 + b[0];
  } s = S * 256;
  if (B[1] >= 0) {s = s + b[1];
  else {s = s + 256 + b[1];
  Short result = (short) s;
return result; /** * Low byte array to short conversion * @param b byte[] * @return Short */public static short Lbytestoshort (byte[] b) {int
  s = 0;
    if (B[1] >= 0) {s = s + b[1];
    else {s = s + 256 + b[1]; } s =S * 256;
  if (B[0] >= 0) {s = s + b[0];
  else {s = s + 256 + b[0];
  Short result = (short) s;
return result;  /** * High byte array converted to float * @param b byte[] * @return float/public static float Hbytestofloat (byte[] b) {int i
  = 0;
  float F = new float (0.0); i = (((b[0]&0xff) <<8 | (B[1]&AMP;0XFF)) &LT;&LT;8) | (B[2]&AMP;0XFF)) <<8 |
  (B[3]&AMP;0XFF);
return f.intbitstofloat (i);  /** * Low byte array converted to float * @param b byte[] * @return float/public static float Lbytestofloat (byte[] b) {int i
  = 0;
  float F = new float (0.0); i = (((b[3]&0xff) <<8 | (B[2]&AMP;0XFF)) &LT;&LT;8) | (B[1]&AMP;0XFF)) <<8 |
  (B[0]&AMP;0XFF);
return f.intbitstofloat (i);
  /** * Align the elements in the byte array in reverse order/public static byte[] Bytesreverseorder (byte[] b) {int length = B.length;
  Byte[] result = new Byte[length];
  for (int i=0; i<length; i++) {result[length-i-1] = b;
return result; /** * Print byte array */public static void PRIntbytes (byte[] bb {int length = Bb.length;
  for (int i=0; i<length; i++) {System.out.print (BB + ""); 

} System.out.println ("");}
  public static void Logbytes (byte[] bb {int length = Bb.length;
  String out = "";
  for (int i=0; i<length; i++) {out = out + BB + ""; }/** * Converts the value of type int to byte order inversion corresponding int value * @param i int * @return int */public static int reverseint (int i) {
  T result = Formattransfer.hbytestoint (Formattransfer.tolh (i));
return result;  /** * Converts the value of the short type to a byte-order inversion corresponding to the short value * @param s short * @return Short/public static short Reverseshort
  s) {Short result = Formattransfer.hbytestoshort (Formattransfer.tolh (s));
return result;  /** * Converts a float value to a byte order inversion corresponding float * @param f float * @return float */public static float reversefloat (float
  f) {Float result = Formattransfer.hbytestofloat (Formattransfer.tolh (f));
return result; } 

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.