-2

I dont understand why the "1<<5" in the following snippet of code, didn't find anything on google

gpio_output_set((1<<5), 0, (1<<5), 0);

Why not use 5? or 32? :)

Thanks for the help

peterretief
  • 2,049
  • 1
  • 15
  • 16
  • 2
    Do you know the value of `1 << 5`? It's definitely not 5. Write several lines of code and check its value. – Yu Hao Apr 02 '15 at 12:46
  • 1
    Look here: http://stackoverflow.com/questions/141525/absolute-beginners-guide-to-bit-shifting – cadaniluk Apr 02 '15 at 12:47
  • 1
    It's called a "shift" operator. Specifically, this is a left-shift operator, and what it does is move (shift) the bits of the left argument (`1`) left a number of places (`100000` = 32) – Eric Hughes Apr 02 '15 at 12:49
  • I know about shift but didnt get it in this case, thanks, been most helpful – peterretief Apr 02 '15 at 12:50
  • 1
    The real question is: 'why not use 0x20?' – William Pursell Apr 02 '15 at 12:53
  • why shift 2 literal numbers? – peterretief Apr 02 '15 at 12:54
  • @WilliamPursell The `gpio` in the function name leads me to believe that `1 << 5` describes pin 5 of a general-purpose I/O port. In that case, it makes some sense to choose a representation that includes the pin number `5`. – Wintermute Apr 02 '15 at 13:03
  • @Wintermute that is correct, it does map to GPIO5 of the esp8266, sometimes defined as something else though, it makes sense now even though I didnt ask the correct question - thanks for the effort – peterretief Apr 02 '15 at 13:41

3 Answers3

2

"Why not use 32?"

Because nobody (including person who wrote the code, one year later) knows what gpio_output_set(32) means. 32 in this case would be what's known as a "magic number", which is programmer slang for a hard-coded number which just sits there in your code, with no rational explanation why, it just magically gets the job done. It is very bad programming practice.

1<<5 on the other hand, is the industry de facto standard way of saying "bit number 5". The intention of the programmer is clear.

Always strive to write self-documenting code, whenever possible.

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

since 1<<5 is off-course a bit-wise operation, so it is far different from decimal 5. The operation 1<<5 will give a decimal value of 32.

userNishant
  • 132
  • 9
0

Value of expression 1<<5 is equal to 32 and equivalent to 2 ^ 5 (in the mathematical notation)

Operator << is bitwise left shift operator.

From the C Standard (6.5.7 Bitwise shift operators)

4 The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros.

I think this record

gpio_output_set((1<<5), 0, (1<<5), 0);

was used instead of

gpio_output_set( 32, 0, 32, 0);

that to show how the value is obtained. But in any case it is a bad idea to use magic numbers like 5.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335