-1

I have this line:

lsb = (char) (intNumber & 0xff);

and I'm confused as to why is it written like

name = (type) (value)

What does it exactly mean, or what is the purpose of defining a variable like that?

underscore_d
  • 6,309
  • 3
  • 38
  • 64
elta
  • 91
  • 2
  • 10
  • Arduino is programmed in C++. – Some programmer dude Oct 30 '17 at 12:26
  • 4
    And to help you with the question, please [get a couple of good beginners books to read](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Oct 30 '17 at 12:27
  • That looks like a cast to me. – Aidenhjj Oct 30 '17 at 12:27
  • 2
    That doesn’t define a variable. –  Oct 30 '17 at 12:28
  • 3
    It's not a definition. It's a so called cast operation. The variable `intNumber` is bitwise ANDed with the literal number `0xff`. The result of this operation is converted to type `char` and assigned to the variable `lsb`. – JonatanE Oct 30 '17 at 12:28
  • The variable definition is elsewere in the code. It should look something like `type name`. What you posted is assigning a value to a variable. – apalomer Oct 30 '17 at 12:28
  • First, no variable is defined in the code you show; the line is not a definition. Second, you are looking at a [C-style cast](http://en.cppreference.com/w/cpp/language/explicit_cast) – Igor Tandetnik Oct 30 '17 at 12:28
  • Until you get a book that covers this basic syntax, read [C++ cast syntax styles](https://stackoverflow.com/questions/32168/c-cast-syntax-styles) – underscore_d Oct 30 '17 at 13:28

3 Answers3

2

lsb = (char) (intNumber & 0xff); intNumber has been and-ed with 0x11111111 and subsequently typecast to 8-bit character, hence it finds the least significant byte of a variable.

Calaf
  • 10,113
  • 15
  • 57
  • 120
0

That is the syntax to typecast a variable e.g.:

float x = 5.55;
int y = (int)x; // in this case, the casting would have happened implicitly
// or 
printf("%d",(int)x);
// this will display 5

Here by specifying constant/variable will be converted to whatever type you mention inside your first pair of brackets.

Anant Sinha
  • 159
  • 1
  • 10
  • It is **a** syntax for casting, among several - specifically, it's the *old* syntax to cast, inherited from C. Proper C++ code should really use one of the specific C++ casts. – underscore_d Oct 30 '17 at 13:27
0

That line means you are casting the result given by the expression on the right forcing it to become a char, in order to fit the variable on the left.

Jul10
  • 503
  • 7
  • 19