What does this line of code do? Const uint32_t goodguys = 0x1 << 0

Can someone tell me what is being done here:

 Const uint32_t goodguys = 0x1 << 0 

I assume this is C ++ and it assigns a tag to a group, but I have never seen this. I am self-taught and it looks very foreign to me.

+2
source share
2 answers

Well, if there are more lines that look like below, then they can be bitmasks .

For example, if you have the following:

 const uint32_t bit_0 = 0x1 << 0; const uint32_t bit_1 = 0x1 << 1; const uint32_t bit_2 = 0x1 << 2; ... 

then you can use the bitwise operator & with bit_0 , bit_1 , bit_2 , ... and another number to see which bits in this other number are on.

 const uint32_t num = 5; ... bool bit_0_on = (num & bit_0) != 0; bool bit_1_on = (num & bit_1) != 0; bool bit_2_on = (num & bit_2) != 0; ... 

So your 0x1 is just a way to indicate that goodguys is a bitmask, since the 0x hexadecimal pointer indicates that the author of the code is thinking specifically about bits instead of decimal digits. And then << 0 used to exactly change what the mask masks (you just change 0 to 1 , 2 , etc.).

+3
source
  • Although base 10 is the usual way to write numbers in a program, sometimes you want to express a number in octal base or in hex base. To write numbers in octal value, precede the value with 0. Thus, 023 actually means 19 in the base 10. To write numbers in hexadecimal, before the value with 0x or 0X. So 0x23 really means 35 in base 10.

So goodguys = 0x1; really means the same as goodguys = 1;

  • Bitwise shift operators shift their first operand to the left (<) or to the right (→) by the number of positions specified by the second operand. Look at the following two statements

    goodguys = 0x1;

    goodguys <2;

The first statement is the same as goodguys = 1; The second statement says that we must shift bits to the left by 2 positions. So we are done with

goodguys = 0x100

which matches goodguys = 4;

Now you can make two statements

goodguys = 0x1;

goodguys <2;

as one operator

goodguys = 0x1 <2;

which is similar to what you have. But if you are not familiar with hexadecimal notation and bitwise shift operators, this will look intimidating.

  • When const is used with a variable, it uses the following syntax:

const variable-name = value;

In this case, the const modifier allows you to assign the initial value to a variable, which cannot be subsequently changed by the program. For instance

const int POWER_UPS = 4;

will assign 4 to the POWER_UPS variable. But if later you try to overwrite this value, for example

POWER_UPS = 8;

You will get a compilation error.

  • Finally, uint32_t means the 32-bit unsigned int type. You will use it if you want your variable to be 32 bits and nothing more.
+3
source

Source: https://habr.com/ru/post/974732/


All Articles