-6

How can I set the least significant bit of an integer in C. For example, I have a 4 data with the following bits

[0] Decimal: 131    Binary: 10000011
[1] Decimal: 11     Binary: 00001011
[2] Decimal: 115    Binary: 01110011
[3] Decimal: 236    Binary: 11101100
[4] Decimal: 245    Binary: 11110101
[5] Decimal: 75     Binary: 01001011
[6] Decimal: 74     Binary: 01001010
[7] Decimal: 116    Binary: 01110100

and I have to change all those four data to be updated with 12 (integer) or 0000 1010 in bits.

So the new updated list would be:

[0] Decimal: 130    Binary: 10000010
[1] Decimal: 11     Binary: 00001011
[2] Decimal: 114    Binary: 01110010
[3] Decimal: 237    Binary: 11101101
[4] Decimal: 244    Binary: 11110100
[5] Decimal: 74     Binary: 01001010
[6] Decimal: 74     Binary: 01001010
[7] Decimal: 116    Binary: 01110100
Sleek13
  • 69
  • 6
  • 1
    It is not clear to me whether you want to *set* the bit (which you can do by or'ing with 1) or *clear* it as your example seems to imply. – LSerni Nov 15 '15 at 23:12
  • How does "updated with 12" equate to "set the least significant bit"? Not getting that part. – kaylum Nov 15 '15 at 23:14
  • The least significant bit in `1010` is the last `0`; What do you mean by "*updated"*? Which operation? – Kenney Nov 15 '15 at 23:14
  • The closest I can come to your example is `if (value < 12) { value &= (~1); }` -- but I would urge you to clarify your question. – LSerni Nov 15 '15 at 23:16
  • It seems like you want to take the bits from the byte with value 12 and distribute them to the least significant bits of your eight bytes in order. Right? – matli Nov 15 '15 at 23:19
  • @lserni that wouldn't explain the change of 75 to 74 – M.M Nov 15 '15 at 23:46
  • `00001010` is 10, not 12 – M.M Nov 15 '15 at 23:47
  • Yes, but 11 does not change, so I assumed 12 to be the criterion for LSB clearing. – LSerni Nov 15 '15 at 23:58

1 Answers1

4

To set bit 0 to one, use

int_var | 1

To reset bit 0 to zero, use

int_var & ~1

The operation in your example doesn't seem consistent:

10000011    
10000010    & ~1
00000001    xor

00001011    
00001011    nop
00000000    xor

01110011   
01110010    & ~1
00000001    xor

11101100    
11101101    & ~1
00000001    xor

11110101    
11110100    & ~1
00000001    xor

01001011    
01001010    & ~1
00000001    xor

01001010
01001010    nop
00000000    xor

01110100
01110100    nop
00000000    xor
Kenney
  • 9,003
  • 15
  • 21