View previous topic :: View next topic |
Author |
Message |
benoitstjean
Joined: 30 Oct 2007 Posts: 566 Location: Ottawa, Ontario, Canada
|
Invert byte / flip bits using single operation |
Posted: Mon Dec 05, 2022 10:30 am |
|
|
Hi guys,
Not sure what I'm doing wrong here but I cannot figure-out what the problem is.... let's say I have this byte:
unsigned int16 Data_ID = 0xFF02; (1111 1111 0000 0010)
I now want to invert the bits. I thought a simple Data_ID != Data_ID; would convert the value to 0x00FD (0000 0000 1111 1101). Didn't work.
Then I tried Data_ID ~= Data_ID and that also has no effect.
In both cases, the value is always 0.
Am I missing something here?
Thanks,
Ben |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Dec 05, 2022 11:12 am |
|
|
Do this:
Code: | Data_ID = ~Data_ID; |
|
|
|
benoitstjean
Joined: 30 Oct 2007 Posts: 566 Location: Ottawa, Ontario, Canada
|
|
Posted: Mon Dec 05, 2022 11:14 am |
|
|
Ah! I had tried it but I think I had screwed-up something else! Works now! Thanks!
Ben |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Fri Dec 09, 2022 3:16 am |
|
|
As a comment here, it is possibly worthwhile looking at what the operators
'do', as to why ! did not work.
! -> logical negate. Makes something that tests as true return a false, and
something that tests as false return true. So won't invert the bits, but the
logical 'result'.
~ -> bitwise not. Inverts every bit in the number. For a 16bit number, same as
^=0xFFFF
This "xor's" each bit with the corresponding bit in the second value. Since
each is 1, this does the same thing as the ~ |
|
|
|