This declaration
unsigned char weight[8] = { 1,2,4,8,16,32,64,128 };
sets masks for bit-wise AND operation. You can rewrite it like
unsigned char weight[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
So this bit-wise AND expression
weight[i] & s;
checks whether the corresponding bit in the object s
is set to 1.
For example if s has the value '\x65' then these operations with the masks
'\x65' & 0x01
'\x65' & 0x04
'\x65' & 0x20
'\x65' & 0x40
will yield a result that unequal to 0.
Pay attention that there is a typo in your code
for (int = 7; i >= 0; i--)
here should be
for (int i = 7; i >= 0; i--)
Here is a demonstrative program
#include <iostream>
#include <iomanip>
void showbits( unsigned char c )
{
unsigned char weight[8] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
for ( int i = 7; i >= 0; i-- )
{
std::cout << ( ( weight[i] & c ) ? '1' : '0' );
}
std::cout << '\n';
}
int main()
{
char c = 'e';
std::cout << "\'" << c << "\' - " << std::hex << static_cast<int>( c ) << '\n';
showbits( c );
return 0;
}
If the system supports ASCII coding then the output will be
'e' - 65
01100101