Data manipulation-extract the high eight bits and low eight bits of data or merge them (implemented in C language)

  When performing data processing, especially those engaged in embedded systems, you often encounter which bit to extract the data, which bit to set the data, to extract the high four bits of the data, to extract the high eight bits of the data, etc. Operation, let's take a look through the actual code.

PART Ⅰ
  takes the high eight bits and low eight bits of a certain data:

void main(void)
{
    
    
	short  test_data;
	unsigned char buf[2];

	buf[0] = test_data;
	buf[1] = test_data >> 8 ;
	printf("buf1 = %d buf2 = %d\n",buf[0], buf[1]);
}

PART Ⅱ
  data synthesis, combining two bytes of data into 16 bit data.
(1) Shift operation

void main(void)
{
    
    
    short new_data;
    unsigned char buf[2];

    buf[0] = 1;
    buf[1] = 1;
    
    new_data = ((*((uint8_t *)buf+ 1<< 8))| *(uint8_t *)buf;
    printf("data = %d\n",new_data);
}

(2) In addition, new data can be obtained by sharing a memory block by using a "union" union. The union uses memory overwriting technology, and can only save the value of one member at a time, because 2 char type data is 16 Bit is exactly the number of bits of short type data, and the data can be merged in the way of union.

union data
{
    
    
    unsigned char buf[2];
    short test_data;
};

void main(void)
{
    
    
    union data test;
    test.buf[0] = 1;
    test.buf[1] = 1;
    
    printf("data = %d\n", test.test_data);
}

Guess you like

Origin blog.csdn.net/qq_33475105/article/details/109151349