1

I'm new to programming and have a question I was hoping I could get some help with.

I have a binary value 0100 0001 0000 0001 which has been assigned to a variable name valhex. I'm supposed to use the bitwise AND operator to make bits 13 through 3 KEEP their current value and ALL other bits are set to zero, then store the result back into the variable valhex. I'm supposed to do this using only one line of C code.

So far all I have is this:

unsigned int valhex = valhex&0000000100000000;

I know this isn't right but this is as far as I can get. I don't know where to put the & symbol in relation to the variable and the binary. I'm also not sure if I'm doing the right thing by making bits 0,1,2,14,15 zeroes. I thank you in advance for any help you might be able to give me.

Matthew
  • 35
  • 1
  • 5

1 Answers1

2

In bitwise AND (if you recall your truth tables), bits that are ANDed with 1 keep their value, bits that are ANDed with a 0, are set to 0. So if you want to keep bits 13-3, your mask needs to have 1s in position 13-3, and 0s in position 2-0. Also note that to specify a binary literal, you need to prefix it with 0b. Also note that you can not declare and use the variable on the same line because it's uninitialized. The end result is this:

unsigned int valhex = 12345; /* some value */
valhex = valhex & 0x3ff8; /* 0x3ff8 = 0b11111111111000 */

Note that unsigned int is longer than 14 bits and you didn't specify what is supposed to happen to bits in position 14 and up. In this case, they'll be set to 0s as well.

nemequ
  • 16,623
  • 1
  • 43
  • 62
Kon
  • 4,023
  • 4
  • 24
  • 38
  • 2
    Prefix `0b` is not standard C. – chux - Reinstate Monica Oct 22 '18 at 01:09
  • @chux I think the idea is more about explaining that it's base 2 rather than actually saying that c has a `0b` prefix. – Ahmed Masud Oct 22 '18 at 02:06
  • @ODYN-Kon Thank you. That makes things clearer. I'm curious, if I wanted to right or left shift the answer in C, would I need an additional line of code or could that just be added to the end of the second line you wrote as >>5 ? – Matthew Oct 22 '18 at 19:30
  • You can do it all on the same line, just make sure to use parentheses so it's clear what you're trying to do. – Kon Oct 22 '18 at 19:33