C


Converting a (void*) buffer to a std::vector

On a project we were recently working on, some legacy C code was producing a (void*) voidBuffer accompanied by its size.
The rest of the project was in C++ and we needed to convert the (void*) voidBuffer to a std::vector<unsigned char> vector.

To do so, we used the following code:


//First cast the (void *) voidBuffer to an (unsigned char *) to implicitly get the element size (1 Byte each)
const unsigned char *charBuffer = (unsigned char *) voidBuffer;
//Then we create the vector (named vectorBuffer) by copying the contents of charBuffer to the vector
std::vector<unsigned char> vectorBuffer(charBuffer, charBuffer + length);

[download id=”4084″]


Alternative to sched_yield()

In case sched_yield() does not seem to work for you or it is not available, you can try calling usleep(0) as a workaround.

int sched_yield(void); from (#include <sched.h>) causes the calling thread to relinquish the CPU. The thread is moved to the end of the queue for its static priority and a new thread gets to run.
From: man 3 sched_yield

int usleep(useconds_t usec); from (#include <unistd.h>) suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.
From: man 3 usleep

Notes

  • Do not use sleep(0) as a workaround as in some older versions of glibc it will not have any effect at all! In those older versions there is a check if the input parameter is set to 0 and if it is then it will do nothing at all. Specifically the code is as follows:
    if (seconds == 0)
     return 0;

    If you want to review the code changes in sleep.c or see how usleep.c is code, download this archive: [download id=”3897″]
    It contains all versions of sleep.c up to today and the latest version of usleep.c.

  • If the calling thread is the only thread in the highest priority list at that time, it will continue to run after a call to sched_yield().
  • Strategic calls to sched_yield() can improve performance by giving other threads or processes a chance to run when (heavily) contended resources (e.g., mutexes) have been released by the caller. Avoid calling sched_yield() unnecessarily or inappropriately (e.g., when resources needed by other schedulable threads are still held by the caller), since doing so will result in unnecessary context switches, which will degrade system performance.

C/C++: Hack to use an array of 4 characters as one unsigned 32 bit integer and increment their value by one

In this scenario, we had 4 unsigned char variables.
The first variable was counting ‘something’.
The second variable was counting how many times the first variable reached its maximum value and then overflowed.
The third variable was counting how many times the second variable reached its maximum value and then overflowed.
Finally, the fourth variable was counting how many times the third variable reached its maximum value and then overflowed.

What we wanted to achieve was to perform this process without using several if statements that check when each variable overflowed and then perform the corrective actions.
The trick that we did to achieve the expected result works on the principle that an array in C/C++ always holds consecutive memory spaces.

What we did was cast the array pointer as a pointer of an unsigned int variable, this allowed us to operate on all 4 bytes at the same time as if they were one.
We can do the same for an array composed of two unsigned short integers.
This trick can of course work on 64bit variables and arrays that contain 8 unsigned char elements or 4 unsigned short elements or 2 unsigned int elements.

++(*((unsigned int *)&t));

Full Example

[download id=”3883″]

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

static inline void increment(unsigned char t[4]) {
  if (t[0] == 0xFF) {
    if (t[1] == 0xFF) {
      if (t[2] == 0xFF) {
        ++t[3];
      }
      ++t[2];
    }
    ++t[1];
  }
  ++t[0];
}

int main() {
  const unsigned int final_limit = (unsigned int) -1; //or 0xFFFFFFFF
  const unsigned int intermediate_limit = 0xABCDEF00;

  {
    unsigned char t[4] = {0, 0, 0, 0};
    printf("%02X %02X %02X %02X - Initial Values\n", t[3], t[2], t[1], t[0]);
    const clock_t start = clock();

    unsigned int i;
    for (i = 0; i < intermediate_limit; ++i) {
      ++(*((unsigned int *)&t));
    }

    printf("%02X %02X %02X %02X - Intermediate Values\n", t[3], t[2], t[1], t[0]);

    for (; i < final_limit; ++i) {
      ++(*((unsigned int *)&t));
    }

    const clock_t end = clock();
    const float seconds = (float) (end - start) / CLOCKS_PER_SEC;
    printf("%02X %02X %02X %02X - Final Values\n", t[3], t[2], t[1], t[0]);
    printf("Seconds elapsed %f\t by casting array of unsigned chars to an unsigned int\n", seconds);
  }

  {
    unsigned char t[4] = {0, 0, 0, 0};
    printf("%02X %02X %02X %02X - Initial Values\n", t[3], t[2], t[1], t[0]);
    const clock_t start = clock();

    unsigned int i;
    for (i = 0; i < intermediate_limit; ++i) {
      increment(t);
    }

    printf("%02X %02X %02X %02X - Intermediate Values\n", t[3], t[2], t[1], t[0]);

    for (; i < final_limit; ++i) {
      increment(t);
    }

    const clock_t end = clock();
    const float seconds = (float) (end - start) / CLOCKS_PER_SEC;
    printf("%02X %02X %02X %02X - Final Values\n", t[3], t[2], t[1], t[0]);
    printf("Seconds elapsed %f\t by using various if statements to control overflow\n", seconds);
  }

  return 0;
}

[download id=”3883″]

Output

00 00 00 00 - Initial Values
AB CD EF 00 - Intermediate Values
FF FF FF FF - Final Values
Seconds elapsed 7.938144 by casting array of unsigned chars to an unsigned int
00 00 00 00 - Initial Values
AB CD EF 00 - Intermediate Values
FF FF FF FF - Final Values
Seconds elapsed 12.820061 by using various if statements to control overflow