unsigned char *adata = (unsigned char*)malloc(500*sizeof(unsigned char));
unsigned char *single_char = adata+100;
How do I change first four bits in single_char to represent values between 1..10 (int)?
The question came from TCP header structure:
Data Offset: 4 bits
The number of 32 bit words in the TCP Header. This indicates where
the data begins. The TCP header (even one including options) is an
integral number of 32 bits long.
Usually it has value of 4..5, the char value is like 0xA0.
These have the assumption that you've initialized *single_char to some value. Otherwise the solution caf posted does what you need.
(*single_char) = ((*single_char) & 0xF0) | val;
(*single_char) & 11110000
-- Resets the low 4 bits to 0| val
-- Sets the last 4 bits to value (assuming val is < 16)If you want to access the last 4 bits you can use
unsigned char v = (*single_char) & 0x0F;
If you want to access the higher 4 bits you can just shift the mask up 4 ie.
unsigned char v = (*single_char) & 0xF0;
and to set them:
(*single_char) = ((*single_char) & 0x0F) | (val << 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With