Network byte order

Source: Internet
Author: User
Tags array to string binary to decimal

BYTE-order, as the name implies the order of bytes, and then say two more than a byte type of data in memory storage order (a byte of data of course there is no need to talk about the order of the problem). In fact, most people in the actual development of the very few direct and byte-order dealings. Byte order is a problem that should be considered only in cross-platform and network programs. In all the articles that introduce the byte order, the byte order is mentioned in two categories: Big-endian and Little-endian, and the reference standard Big-endian and Little-endian are defined as follows: a) Little-endian is the low-bit bytes emitted at the lower address of the memory, high-bit bytes emitted in the memory of the higher address. b) The Big-endian is the high-bit byte emitted at the low address of the memory, and the low byte is discharged at the upper address of the memory. c) Network byte order: The TCP/IP layer protocol defines the byte order as Big-endian, so the byte order used in the TCP/IP protocol is often referred to as the network byte order.

Java byte-orderBig-endian, Little-endian are related to multibyte-type data, such as the Int,short,long type, but have no effect on single-byte data byte. Big-endian is low-byte emissions at the high end of memory, high-bit bytes emitted at the low end of memory. And Little-endian is the opposite. For example, int a = 0x05060708 is 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 from 05big-endian , Little-endian and CPU, each CPU is not Big-endian is Little-endian. The IA architecture is Little-endian in the CPU, while PowerPC, SPARC, and Motorola processors are Big-endian. This is actually called the host byte order. While the network byte order refers to the data on the network transmission is large or small, network byte order in the Internet is Big-endian. The so-called Java byte order refers to the order in which multibyte-type data is stored in a Java virtual machine, and the Java byte-order is Big-endian. Therefore, when writing communication programs in C + +, it is important to use htonl and htons to convert the integer and short integer data from the host byte order to the network byte order before sending the data. After receiving the data for integer and short integer data, you must call Ntohl and Ntohs to implement the conversion from the network byte order to the host byte order. If one side of the communication is a Java program, and the other one is a/C + + program, you need to convert the byte order on the C/E + + side using the above methods, while the Java side does not need to do any processing because the Java byte order and network byte order are Big-endian, as long as C + + One side can be converted correctly (before sending from the host order to the network order, the reception of the reverse transformation). If both sides of the communication are Java, then the problem of the byte order is not considered at all. If the network is all POWERPC,SPARC and Motorola CPU host then there is no problem, but due to the fact that there is a large number of IA architecture of the CPU, so there are frequent data transmission errors. The problem at the beginning of the article is that because the program runs on the PC server of the X86 architecture, one end of the sending data is implemented in C, and the receiving end is implemented in Java, and the sender does not convert from host byte order to network byte order before sending the data. In this way, the receiving end receives Little-endian data, and the data interpretation is naturally wrong. The details are as follows, the actual data sent is23578 Send side Send data: 1 A 5C after receiving the data received, according to Big-endian to explain the specific data is how much? You have to calculate and compare yourselves! ===============================================================================================big Endian and Little endian talks about the problem of byte order, which inevitably involves two major CPU factions. That's Motorola's PowerPC series CPU and Intel's x86 series CPUs. The PowerPC series uses big endian to store data, while the x86 series stores data in little endian mode[1]Why pay attention to the problem of byte order? You might ask. Of course, if you write a program that only runs under a stand-alone environment and doesn't deal with other people's programs, you can completely ignore the existence of the byte-order. But what if your program has to interact with other people's programs? Especially when you apply the results of your computer operation to a group of computers. Here I would like to speak two languages. In a program written in the C + + language, the data is stored in a sequence that is related to the CPU on which the build platform resides, while Java programs only use the big endian to store data. Imagine what would happen if you wrote a program written under the x86 platform with a C + + language that would interoperate with someone else's Java program? Take the above 0x12345678, your program passed to someone else's data, will point to the 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 into 0x78563412. What the? Turned into another number? Yes, that's the result. Therefore, it is necessary to convert the byte order before your C program is passed to the Java program.[1] advantages and disadvantages of Big-endian and Little-endianBig-endian Pros: By first extracting high-order bytes, you can always determine whether the number is positive or negative by looking at the byte at offset 0. You don't have to know how long this number is, or you don't have to go through some bytes to see if the value contains a sign bit. This value is stored in the order in which they are printed, so functions from binary to decimal are particularly effective. Therefore, for different requirements of the machine, in the design of access mode will be different.[1]Little-endian Advantages: Extracting one, two, four, or longer byte data assembly instructions in the same way as all other formats: first, the lowest bit byte is fetched at the offset address of 0, because the address offset and the number of bytes are one-to-two relationships, The mathematical function of multiple precision is relatively easy to write.[1]If you increase the value of the number, you may increase the number on the left (the high-level non-exponential function requires more numbers). Therefore, it is often necessary to increase the number of two digits and move all Big-endian in the memory, moving all numbers to the right, which increases the workload of the computer. However, the non-important bytes in the memory using Little-endian can exist in its original position, and the new number can exist in its right high address. This means that some computations in the computer can become simpler and faster.
Coincidentally, allNetwork protocolIt's all about using big endian to transfer data. So sometimes we'll call it the big endian way of the Web .byte order. When two units are used in differentbyte orderhost communication, the byte order must be converted into a network byte order before transmitting the data. Four conversions are available in ANSI Cbyte orderthe macro.

========================================================================================================/*** Communication Format Conversion * * Java and some Windows programming languages such as C, C + +, Delphi written by the network program to communicate, you need to convert * high, low-byte conversion * Windows byte order starts with low byte * Linux,unix byte order starts with high byte * Java, regardless of platform change, is high byte beginning */public class Formattransfer {/*** int to low byte before, high byte in the following byte array * @param n int* @return 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;} /*** int to high byte in front, low byte after byte array * @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 in front, high byte after byte array * @param n short* @return byte[]*/public static byte[] Tolh (short n) {byte[] b = new byte[2 ];b[0] = (byte) (n & 0xff); b[1] = (byte) (N >> 8 & 0xff); return b;} /*** convert short to high byte in front, low byte after byte array * @param n short* @return byte[]*/public static byte[] Tohh (short n) {byte[] b = new byte[2 ];B[1] = (byte) (n & 0xff); b[0] = (byte) (n >> 8 & 0xff); return b;} /*** int to high byte in front, low byte after 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] = (byt e) ((0xff00 & i) >> 8); abyte0[1] = (byte) ((0xff0000 & i) >> +); abyte0[0] = (byte) ((0xff000000 & i) >>; return abyte0;} *//*** float to low byte in front, high byte after byte array */public static byte[] Tolh (float f) {return Tolh (Float.floattorawintbits (f));} /*** float to high byte in front, low byte after byte array */public static byte[] Tohh (float f) {return tohh (Float.floattorawintbits (f));} /*** string to byte array */publicStatic byte[] Stringtobytes (String s, int length) {while (S.getbytes (). length < length) {s + = "";} return S.getbytes ();} /*** converts a byte array to string* @param b byte[]* @return string*/public static String bytestostring (byte[] b) {StringBuffer 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) {return s.getbytes ();} /*** converts a high-byte array to 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 + n + b;} s = S * 256;} if (B[3] >= 0) {s = s + b[3];} else {s = s + n + b[3];} return s;} /*** converts a low-byte array to 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 + n + b[3-i];} s = S * 256;} if (B[0] >= 0) {s = s + b[0];} else {s = s + n + 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 + n + b[0];} s = S * 256;if (b[1] >= 0) {s = s + b[1];} else {s = s + n + 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 + n + b[1];} s = S * 256;if (B[0] >= 0) {s = s + b[0];} else {s = s + n + b[0];} Short result = (short) s;return result;} The/*** high-byte array is 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]&0xff); return f.intbitstofloat (i);} /*** low-byte array is 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]&0xff); return f.intbitstofloat (i);} /*** the elements in a byte array in reverse order */public static byte[] Bytesreverseorder (byte[] b) {int length = b.length;byte[] result = new Byte[len gth];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.ou T.print (BB + "");} System.out.println ("");} public static void Logbytes (byte[] bb) {int length = Bb.length; String ut = ""; for (int i=0; i<length; i++) {ut = out + BB + "";}} /*** converts the value of type int to a byte-order reversal of the corresponding int value * @param i int* @return int*/public static int reverseint (int i) {int result = FORMATTRANSFE R.hbytestoint (Formattransfer.tolh (i)); return result;} /*** converts the value of the short type to a short value corresponding to the byte order reversal * @param s short* @return short*/public static short reverseshort (short s) {short result = Formattransfer.hbytestoshort (Formattransfer.tolh (s)); return REsult;} /*** converts a value of type float to a byte-order upside-down corresponding to the float value * @param f float* @return float*/public static float reversefloat (float f) {float result = Formattransfer.hbytestofloat (Formattransfer.tolh (f)); return result;}}

Network byte order

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.