Code Comments
Programming Forum and web based access to our favorite programming groups.Hi Folks
I was looking for a way to test bit settings in a Hex value.
i.e.
Hex value 0x07
Bit mask 0x05
If at least all bits in mask are set in value then true.
Using expr,
expr 0x07 & 0x05, gives 5
which reading from the man page is as expected.
Now if we do
expr 0x04 & 0x05, gives 4
which is not what I wanted to see but still correct from the description.
The only way I can think of doing what I want is
if {[expr $value & $bitpattern ] == $bitpattern } {
#Then all present
} else {
#Not all there
}
Any body thing of a better way?
Thanks
Derek
Post Follow-up to this messageDerek <derek.philip@csr.com> wrote:
> The only way I can think of doing what I want is
> if {[expr $value & $bitpattern ] == $bitpattern } {
You're already quite near!
The first argument to "if" is already treated like an expr,
so you can "simplify" this to:
if {($value & $bitpattern) == $bitpattern} { ...
which is likely among the best you can get.
Oh, there is still an alternative, but you would
have to swap the "then" and "else" clause for this:
if {($value ^ $bitpattern) & $bitpattern} {
# some bits were missing in $value
# Incidentally, the expression evaluates to
# exactly the set of missing bits :-)
} else {
# all required bits were set in $value
}
Post Follow-up to this messageAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at> wrote in message news:<slrnchn7v1.nab.avl@ga
mma.logic.tuwien.ac.at>...
> Derek <derek.philip@csr.com> wrote:
>
> You're already quite near!
> The first argument to "if" is already treated like an expr,
> so you can "simplify" this to:
> if {($value & $bitpattern) == $bitpattern} { ...
> which is likely among the best you can get.
>
> Oh, there is still an alternative, but you would
> have to swap the "then" and "else" clause for this:
> if {($value ^ $bitpattern) & $bitpattern} {
> # some bits were missing in $value
> # Incidentally, the expression evaluates to
> # exactly the set of missing bits :-)
> } else {
> # all required bits were set in $value
> }
Thanks for the comments Andreas
I did look at the if statement early on but my understanding of what
was happening wasn't clear.
I think I'll use your "if" sugestion with the & and test for equality
as it is slighty easier to understand for the average joe who may look
at the scripts I'm writing.
Derek
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.