c++ - How to determine whether a 32-bit/64-bit value has a certain 16-bit value? -
questions
consider following 32-bit , 64-bit values:
uint32_t ival32 = 0x ab cd 12 34; uint64_t ival64 = 0x ab cd 12 34 56 78 ca be;
- how determine whether
ival32
contains 16-bit (word) value?let's0xcd12
. - how determine whether
ival64
contains 16-bit (word) value?let's0x3456
.
update 1 (added later)
word value checked might anywhere in0xcd12
ival32
in every word boundary.word value checked might anywhere in0x3456
ival64
in every word boundary.
update 2 (added later)
i admit ridiculous mistake in question. in previous example, word values checked not in word boundaries in ival32
, ival64
. therefore, correction are:
- for
ival32
, word value checked can either0xabcd
or0x1234
. thus, example,0xcd12
shouldn't found inival32
. - for
ival64
, word value checked can 1 of following:0xabcd
or0x1234
or0x5678
or0xcabe
. thus, example,0xcd12
or0x3456
or0x78ca
shouldn't found inival64
.
remarks
- solutions intended used in function searches 16-bit character in unicode string. in x86, function reads 2 characters @ time; , in x64, function reads 4 characters @ time.
- i ask because noticed implementation of glibc strchr() (that works 8-bit character) tries test longword @ time, didn't understand code well.
bool contains (uint32_t haystack, uint16_t needle) { return ((haystack & 0xffff) == needle) || (((haystack >> 16) & 0xffff) == needle); } bool contains (uint64_t haystack, uint16_t needle) { return ((haystack & 0xffff) == needle) || (((haystack >> 16) & 0xffff) == needle) || (((haystack >> 32) & 0xffff) == needle) || (((haystack >> 48) & 0xffff) == needle); }
Comments
Post a Comment