Search code examples
cmemset

memset bytewise instead of integer ( 4 bytes )


I am struggling to find the answer to this:

#define BUFLEN 8
unsigned short randombuffer[BUFLEN];    
memset(randombuffer, 200 , BUFLEN );
printf("%u", randombuffer[0]);

I am getting the answer as 51400 although I was expecting 200. After debugging I found out that the randombuffer is filled with 0xC8 for the first 8 entries. Hence 0xC8C8 is 51400. I was however expecting 0x00C8 for each index in the array. What am I doing wrong?


Solution

  • memset fills bytes, but it looks like you want to fill words. I don't know if there's a memset-like function built in for this, so you might have to do repeated memset/memcpy instead. Note that if you feel comfortable writing inline assembler you could probably do this pretty efficiently yourself in machine code - although a tight loop using pointers in C is probably close to as fast.