void * memset ( void * ptr, int value, size_t num );
memset()
sets the first num bytes of ptr to value. I want to use memset()
to set all bytes of a void buffer to:
00000000
11111111
10101010
01010101
For "00000000" I can use
memset(buffer, '0', BUF_LENGTH);
But am I right to assume
memset(buffer, '1', BUF_LENGTH);
won't end in "11111111", but in "00000001"? I've read that '-1' would do the trick, but why? And what value would i need to set bitwise 10101010 or 01010101?
memset operates on a byte-by-byte basis.
To zero the memory use:
memset(buffer, 0, BUF_LENGTH);
To set each byte to the value 1 use:
memset(buffer, 0x01, BUF_LENGTH);
For the binary pattern 10101010 use:
memset(buffer, 0xAA, BUF_LENGTH);
For the binary pattern 01010101 use:
memset(buffer, 0x55, BUF_LENGTH);
To set all bits in the buffer to 1 use:
memset(buffer, 0xFF, BUF_LENGTH);
BUF_LENGTH would be the length used in the array definition, eg
#define BUF_LENGTH 256
char buffer[BUF_LENGTH];
or what you used as length in dynamic memory allocation:
#define BUF_LENGTH 256
char *buffer = malloc(BUF_LENGTH);
Do not quote the 0 as in your code example, as this represents the ascii character '0', which has the value 0x30 (see http://www.asciitable.com/ ).
If this is C++, use binary literals, for instance 0b10101010
and 0b01010101
.
If it is C, translate to hexadecimal, 0xAA
and 0x55
.
(Using '0'
and '1'
will most likely result in 00110000 and 00110001, respectively.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.