Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Huuugo25208yIf 0 and 1 are considered booleans in that language you could just negate them:
recvalues[0] = ! recvalues[0]; -
I could agree with you, but typing 0x1 instead of just 1 (recValues ^= 1) is just to make it look unreadable on purpose, isn't it?
-
Oh wait. It just hit me. The array contains chars! WTF.
'0' ! = 0
None of the answers above are correct (including mine), are they?
If so,
x = x == '0' ? '1' : '0'
Would be the easiest -
@Joserc87 More out of habit. I'm a Computer Engineer, so I use hex a lot.
I also use bitwise operators a lot, so that's where the solution comes from.
In the actual implementation I wrapped 0x1 in a macro with an easy-to-read name so nobody wonders what the 0x1 does. -
I mean, yes: Using bitwise operators IS a little bit more unreadable. But the speedup in compiled code is significant -- especially if it gets executed inside a loop. Usually when I use bitwise operators I put a comment in.
-
If the performance matters then yes, totally, get rid of the conditional jumps!
But then again, if it really matters and it's in an algorithm you can bundle that array into a byte or a word? I'm curious about what this actually does -
@Joserc87 Switches a '0' to a '1' and vice versa.
The actual code was part of a file I/O program. The actual program is meant to toggle a GPIO pin, on or off.
So the program has to: Read the bit, change it, then write it back. -
At first I really thought the program was wrong because of the char to int jump.. but it's right. I'm an amateur embedded systems engineer from the CS world. It took me a bit to realize you are just flipping the last bit of the character. Duh!
-
I compiled the top-suggested alternative solutions. The conditional assignment is only a little bit faster than if/else. Two assembly instructions fewer, to be exact.
The bitwise operation was 30% faster than the conditional assignment. -
Double-A4358yWhy does the bitwise operator work there? The values are char, so just arbitrary ASCII bit patterns... Seems like a coincidence.
-
'0' is 0x30 and '1' is 0x31 in ASCII
The ASCII characters were arranged so you can do things like iterate through them in ascending order. Other cool things too:
'a' is 0x61
'A' is 0x41
so to convert between lower case and upper case just add or subtract 0x20. -
in binary:
'1' is 0011 0000
'0' is 0011 0001
so Exclusive-Or either with 1 flips bit 0 and only bit zero
When I see a coworker do this:
if( recValues[0] == '0' )
{
recValues[0] = '1';
}
else if( recValues[0] == '1' )
{
recValues[0] = '0';
}
I replace it with this:
recValues[0] ^= 0x1;
Note: The recValues[0] is guaranteed to contain only '0' or '1'
undefined