"Extract high eight int the" learn from the beginning

Today there is a school brother asked a question, how to extract int in the high eight.

This is a very basic question, just messing around with the bit operation a few came out.

See this issue, I do not know what some had thought, thought of a Sao operation, with memcpy the int inside of a string. . Admit it, you are a cancer. ヾ(· ω · `.) 

Method is as follows

#include <cstdio> 
#include <CString>
 int main () {
     int A = 0xaabbccff ;
     char CH [ . 4 ]; 
    the memcpy (CH, & A, . 4 ); 
     for ( int I = 0 ; I < . 4 ; I ++ ) { 
        the printf ( " CH [D%] = # X% " , I, 0xFF & ch [i]);
         / * % X will cast ch [i] is of type int, if the first byte 1 will be supplemented before 1 , so only eight to take low * / 
        / * the OUTPUT: 
       CH [0] = 0xFF CH [. 1] = CH 0xCC [2] = 0xbb CH [. 3] = 0xAA 
     * /
    }
    return 0;
}  

But I told the school brother said to take high eight straight to take ch [0], the output from the results, my answer is wrong, all of a sudden not figured out why.

Is known only later byte order. As if to touch my knowledge the blind spot (you do not understand anything has always been a chicken dish) , I went to check a bit.

In fact, total on the following words:

There are two data stored in computer hardware manner: big-endian byte order (big endian) and little endian (little endian).

Big endian: the high byte, the lower byte, the value of which is read-write method humans.

Little-endian: low byte first, high byte after that is stored in the form of 0x1122.

Computer processing circuit low byte first, high efficiency, because the calculations are from the lowest bit. Therefore, the internal processing is little endian computers.

for example

#include <cstdio>
#include <cstring>
int main(){
    int a = 0xaabbccdd;
    char c;
    c = a;
    printf("%#x\n", 0xff&c);
    /* OUTPUT:
       0xdd
    */    
}  

But some cpu is not strictly for processing data in accordance with the little-endian, so my cancer method, although you can extract the value of each byte, but the value of the index on different machines may not be the same, and so It can not be applied.

Guess you like

Origin www.cnblogs.com/HDMaxfun/p/11408392.html