Zookeeper
1. Input one integer data into a buffer char * buffer for cross-platform transmission. Write buffer and read buffer are implemented in binary and text modes respectively.
----> Transmission in the network is in the big-end mode, but on the local machine it may be in the small-end mode. This requires first judgment.
# Include <stdio. h> # include <stdlib. h> # include <string. h> char buf1 [1024]; char buf2 [1024]; int ascii_write_to (INT); int binary_write_to (INT); int binary_read_from (); int ascii_read_from (); int main (INT argc, const char * argv []) {int A = 0x12345678; binary_write_to (a); ascii_write_to (); printf ("% x \ n", binary_read_from (), ascii_read_from (); Return 0;} int ascii_write_to (INT data) {sprintf (buf1, "% d ", da Ta); return data;} int binary_write_to (INT data) {short int x = 0x0001; char * P = (char *) & X; If (* P) // small-end mode {int TMP = (data> 24) & 0xff | (data> 8) & 0xff00 | (Data <8) & 0xff0000 | (Data <24) & 0xff000000; * (int *) buf2 = TMP;} else // large-end mode memcpy (buf2, & Data, sizeof (data )); return data;} int ascii_read_from () {int TMP; sscanf (buf1, "% d", & TMP); Return TMP;} int binary_read_from () {int DATA = * (int *) Buf2; unsigned short a = 0x0001; char * P = & A; If (! (* P) {int TMP = data; // large-end machine} else // small-end machine {int TMP = (data> 24) & 0xff | (data> 8) & 0xff00 | (Data <8) & 0xff0000 | (Data <24) & 0xff000000;} return TMP ;}
Streams can be divided into two types: Text streams (ASCII) and binary streams. A text stream can contain up to 255 characters. The carriage return/line feed is converted to the line break "\ n", and vice versa. The binary stream is non-explanatory. It processes one character at a time and does not convert characters.
Generally, text streams are used to read and write standard text files, output characters to a screen or printer, or accept keyboard input; the binary stream is used to read and write binary files (examples or word processing documents), read mouse input, or read and write the modem.
The binary and text formats of integer data are transmitted.