Domanda

I just have a quick question about what this code mean. Sorry, been reading other posts but I couldn't fully grasp the concept since none seems to resemble this piece of code that I'm currently working in my embedded system.

int8u buf[1024];
memset(buf, 0, sizeof(buf));
*((int16u*)&buf[2]) = 0xbb01;

can someone explain to me what these lines mean?

È stato utile?

Soluzione

It basically interprets the array of bytes buf as 16-bit words and then changes the second word to 0xbb01. Alternative representation:

int8u buf[1024];
memset(buf, 0, sizeof(buf));

int16u *words = buf;
buf[1] = 0xbb01;

&buf[2] takes the address to the second byte in buf. Then the cast to (int16u *) informs the compiler that the result is to be treated as a 16-bit unsigned integer. Finally, the memory on that address is set to 0xbb01.

Depending on the endianness of your system, the contents of buf could then be 0x00, 0x00, 0xbb, 0x01 or 0x00, 0x00, 0x01, 0xbb (followed by more NULs due to the memset()).

Altri suggerimenti

Please see the comment of the code for explanation

int8u buf[1024];                  // intializing int array of size 1024 in RAM. 

memset(buf, 0, sizeof(buf));      // fill in buffer with zero. 

(int16u*)&buf[2] is a type casting for pointer which points to int16. here casting is given to &buf[2] i.e. address of buf[2].

*((int16u*)&buf[2]) = 0xbb01;  //  updating content of int16 -two byte intger starting at buf2

Why this is done ?

This is done as buf array was created is of int8u. and now we need to update int16 value 0xbb01. To do this, in above code we have created int16 pointer.

Step by Step simplification of above pointer

  1. ((int16u)&buf[2]) = 0xbb01;
  2. updating content of ((int16u*)&buf[2]) by 0xbb01
  3. &buf[2] is pointer to int16u and update its value by 0xbb01
  4. update value at buf[2],buf[3] by 0xbb01.[#]

[#]: exact content of buf[2], buf[3] will depend on type of core architecture: big endian or small endian.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top