Reputation: 536
Is there a logical equivalent to:
if(byte != 0x00 || byte != 0xFF)
if(byte != 0x00 && byte != 0xFF)
I'm at my program memory limit and can use every optimalisation :)
To explain with words, can you check with a logic function if all bits are same (so all 0 or all 1)?
Thanks!
Upvotes: 1
Views: 2883
Reputation: 477100
Maybe (unsigned char)(byte + 1) > 1
? Assuming you mean &&
, of course. And assuming that CHAR_BIT == 8
, if you want "all bits set" to mean 0xFF
.
Upvotes: 6
Reputation: 6926
I found that given your original code GCC is smart enough to produce something similar to Kerrek SB's answer when using -O2
:
movzbl 8(%ebp), %eax
subl $1, %eax
cmpb $-3, %al
setbe %al
which is basically equivalent to:
((unsigned char)byte - 1) <= -3 // or 0xFD
Upvotes: 2
Reputation: 279265
Assuming that byte
has an unsigned 8-bit type [Edit: and assuming you meant &&
, not ||
], you could try:
!((uint8_t)(byte+1) <= 1)
Obviously it's not possible to say whether this will produce smaller code, you just have to try it and see. No doubt other people can come up with other logically-equivalent expressions.
You can also look at what your compiler has produced, and if you suspect that your compiler's optimization isn't very good look at what other, better compilers produce. That might give you ideas for other expressions that are logically equivalent.
Upvotes: 6
Reputation: 62068
The condition is always true.
I seriously doubt that the above check can be compacted much.
At the instruction level the if would look something like:
; if(byte != 0x00 || byte != 0xFF)
cmp byte, 0
jnz ifbody
cmp byte, 0xFF
jz skipifbody
ifbody:
;{
; if body
;}
skipifbody:
There are about 4 instructions here. There isn't much to optimize here.
I would look for other places in the code to optimize things for size. The first thing to look at would be the data, not the code, though.
Upvotes: 2