So my problem was that I was trying to use a truncation hash function as a collision index increment/decrement... I had to use it as the first main function, and use a more uniform hash function as the second hash function in its place.
My corrected code is below:
// ============================ HASH FUNCTIONS ============================ \\
// Hash function 1 (Base-26)
int Hash_1(char *key2)
{
int index;
index = (int)((key2[0] - 'A' + 1) * pow(26, 3)) + ((key2[1] - 'A' + 1) * pow(26, 2)) + ((key2[2] - 'A' + 1) * 26) + ((key2[3] - 'A' + 1));
return (index % TABLESIZE);
}
// Hash function 2 (Folding)
int Hash_2(char *key2)
{
int index;
index = ((key2[0] - 'A' + 1) * (key2[1] - 'A' + 1)) + ((key2[2] - 'A' + 1) * (key2[3] - 'A' + 1));
return (index % TABLESIZE);
}
// Hash function 3 (Truncation)
int Hash_3(char *key2)
{
int index;
index = ((key2[1] - 'A' + 1) * (key2[2] - 'A' + 1));
return (index % TABLESIZE);
}
// ========================= DOUBLE HASH FUNCTIONS ========================= \\
// Double hash 1 (Linear Probing)
int ProbeDec_1(char *key2)
{
return 1;
}
// Double hash 2 (Middle Squaring)
int ProbeDec_2(char *key2)
{
int index;
index = (int)pow(((key2[1] - 'A' + 1) + (key2[2] - 'A' + 1)), 2);
return (index % TABLESIZE);
}
// Double hash 3 (Division)
int ProbeDec_3(char *key2)
{
int index;
int primeNum = 7;
index = max((key2[3] / primeNum), 1) % primeNum;
return (index % TABLESIZE);
}
You can create a perfect "hash" for 4-letter strings.
There are less than 32 letters in the latin alphabet, there are less than 64 letters in the latin alphabet if you distinguish between upper and lower case letters.
Why mention 32 and 64? Because they are fifth and sixth powers of two.
We can create a 32 bit integer that uniquely represents a 4-letter word (distinguishing between upper and lower letters) as follows:
bits 0 to 5 encode the first letter of the string
bits 6 to 11 encode the second
bits 12 to 17 encode the third
bits 18 to 23 encode the fourth
bits 24 to 31 are set to 0
By encode, I mean something like:
"A" is encoded as 000000
"a" is encoded as 000001
"B" is 000010
"b" is 000011
and so on. We know we can fit all the letters in whatever encoding you want because there are fewer letters than there are available bit arrangements.
You can even encode each letter as key - 'A' + 1, as you seem to prefer.
I would strongly suggest you create a function that takes a character and returns its encoded value. Generally, if you find yourself writing the same piece of code in more than 3 places, you should consider making it a function.
Equally important, since writing hash functions is mostly about bit-fiddling, you should learn how to use the shift operators < and > instead of pow.
You should also learn about integer operations.
What exactly do you thing 1 / (1 - (key2[2] - 'A' + 1)) can possibly return?
None of your functions can be called "hash functions".
If you want to use something like "truncation" or "division" you should first figure out what that means.
Related
The following code will decrypt a caesar encrypted string given the ciphertext and the key:
#include <iostream>
std::string decrypt(std::string cipher, int key) {
std::string d = "";
for(int i=0; i<cipher.length();i++) {
d += ((cipher[i]-65-key+26) %26)+65;
}
return d;
}
int main()
{
std::cout << decrypt("WKLVLVJRRG", 3) << std::endl; // THISISGOOD
std::cout << decrypt("NBCMCMAIIX", 20) << std::endl; // THISISGOOD
}
I'm having trouble to understand the operations performed to compute the new character ASCII code at this line:
d += ((cipher[i]-65-key+26) %26)+65;
The first subtraction should shift the number range
Then we will subtract the key as how the Caesar decryption is defined
We add 26 to deal with negative numbers (?)
The module will limit the output as the range of the ASCII numbers is 26 length
We come back to the old range by adding 65 at the end
What am I missing?
If we reorder the expression slightly, like this:
d += (((cipher[i] - 65) + (26 - key)) % 26) + 65;
We get a formula for rotating cipher[i] left by key:
cipher[i] - 65 brings the ASCII range A..Z into an integer range 0..25
(cipher[i] - 65 + 26 - key) % 26 rotates that value left by key (subtracts key modulo 26)
+ 65 to shift the range 0..25 back into ASCII range A..Z.
e.g. given a key of 2, A becomes Y, B becomes Z, C becomes A, etc.
Let me give you a detailed explanation about Caesar Cipher for understanding that formular. I will also show ultra simple code examples, but also more advanced one liners.
The biggest problems are potential overflows. So, we need to deal with that.
Then we need to understand what Encryption and decryption means. If encryption will shift everthing one to the right, decryption will shift it back to left again.
So, with "def" and key=1, the encrpyted string will be "efg".
And decrpytion with key=1, will shift it to left again. Result: "def"
We can observe that we simply need to shift by -1, so the negative of the key.
So, basically encryption and decryption can be done with the same routine. We just need to invert the keys.
Let us look now at the overflow problematic. For the moment we will start with uppercase characters only. Characters have an associated code. For example, in ASCII, the letter 'A' is encoded with 65, 'B' with 66 and so on. Because we do not want to calculate with such number, we normalize them. We simply subtract 'A' from each character. Then
'A' - 'A' = 0
'B' - 'A' = 1
'C' - 'A' = 2
'D' - 'A' = 3
You see the pattern. If we want to encrypt now the letter 'C' with key 3, we can do the following.
'C' - 'A' + 3 = 5 Then we add again 'A' to get back the letter and we will get 5 + 'A' = 'F'
That is the whole magic.
But what to do with an overflow, beyond 'Z'. This can be handled by a simple modulo division.
Let us look at 'Z' + 1. We do 'Z' - 'A' = 25, then +1 = 26 and now modulo 26 = 0 then plus 'A' will be 'A'
And so on and so on. The resulting Formula is: (c-'A'+key)%26+'A'
Next, what with negative keys? This is also simple. Assume an 'A' and key=-1
Result will be a 'Z'. But this is the same as shifting 25 to the right. So, we can simply convert a negative key to a positive shift. The simple statement will be:
if (key < 0) key = (26 + (key % 26)) % 26;
And then we can call our tranformation function with a simple Lambda. One function for encryption and decrytion. Just with an inverted key.
And with the above formular, there is even no need to check for a negative values. It will work for positive and negative values.
So, key = (26 + (key % 26)) % 26; will always work.
Some extended information, if you work with ASCII character representation. Please have a look at any ASCII table. You will see that any uppercase and lowercase character differ by 32. Or, if you look in binary:
char dez bin char dez bin
'A' 65 0100 0001 'a' 97 0110 0001
'B' 66 0100 0010 'b' 98 0110 0010
'C' 67 0100 0011 'b' 99 0110 0011
. . .
So, if you already know that a character is alpha, then the only difference between upper- and lowercase is bit number 5. If we want to know, if char is lowercase, we can get this by masking this bit. c & 0b0010 0000 that is equal to c & 32 or c & 0x20.
If we want to operater on either uppercase or lowercase characters, the we can mask the "case" away. With c & 0b00011111 or c & 31 or c & 0x1F we will get always equivalents for uppercase charcters, already normalized to start with one.
char dez bin Masking char dez bin Masking
'A' 65 0100 0001 & 0x1b = 1 'a' 97 0110 0001 & 0x1b = 1
'B' 66 0100 0010 & 0x1b = 2 'b' 98 0110 0010 & 0x1b = 2
'C' 67 0100 0011 & 0x1b = 3 'b' 99 0110 0011 & 0x1b = 3
. . .
So, if we use an alpha character, mask it, and subtract 1, then we get as a result 0..25 for any upper- or lowercase character.
Additionally, I would like tor repeat the key handling. Positive keys will encrypt a string, negative keys will decrypt a string. But, as said above, negative keys can be transormed into positive ones. Example:
Shifting by -1 is same as shifting by +25
Shifting by -2 is same as shifting by +24
Shifting by -3 is same as shifting by +23
Shifting by -4 is same as shifting by +22
So,it is very obvious that we can calculate an always positive key by: 26 + key. For negative keys, this will give us the above offsets.
And for positve keys, we would have an overflow over 26, which we can elimiate by a modulo 26 division:
'A'--> 0 + 26 = 26 26 % 26 = 0
'B'--> 1 + 26 = 27 27 % 26 = 1
'C'--> 2 + 26 = 28 28 % 26 = 2
'D'--> 3 + 26 = 29 29 % 26 = 3
--> (c + key) % 26 will eliminate overflows and result in the correct new en/decryptd character.
And, if we combine this with the above wisdom for negative keys, we can write: ((26+(key%26))%26) which will work for all positive and negative keys.
Combining that with that masking, could give us the following program:
const char potentialLowerCaseIndicator = c & 0x20;
const char upperOrLower = c & 0x1F;
const char normalized = upperOrLower - 1;
const int withOffset = normalized + ((26+(key%26))%26);
const int withOverflowCompensation = withOffset % 26;
const char newUpperCaseCharacter = (char)withOverflowCompensation + 'A';
const char result = newUpperCaseCharacter | (potentialLowerCaseIndicator );
Of course, all the above many statements can be converted into one Lambda:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
// Simple function for Caesar encyption/decyption
std::string caesar(const std::string& in, int key) {
std::string res(in.size(), ' ');
std::transform(in.begin(), in.end(), res.begin(), [&](char c) {return std::isalpha(c) ? (char)((((c & 31) - 1 + ((26 + (key % 26)) % 26)) % 26 + 65) | (c & 32)) : c; });
return res;
}
int main() {
std::string test{ "aBcDeF xYzZ" };
std::cout << caesar(test, 5);
}
The last function can also be made more verbose for easier understanding:
std::string caesar1(const std::string& in, int key) {
std::string res(in.size(), ' ');
auto convert = [&](const char c) -> char {
char result = c;
if (std::isalpha(c)) {
// Handling of a negative key (Shift to left). Key will be converted to positive value
if (key < 0) {
// limit the key to 0,-1,...,-25
key = key % 26;
// Key was negative: Now we have someting between 0 and 26
key = 26 + key;
};
// Check and remember if the original character was lower case
const bool originalIsLower = std::islower(c);
// We want towork with uppercase only
const char upperCaseChar = (char)std::toupper(c);
// But, we want to start with 0 and not with 'A' (65)
const int normalized = upperCaseChar - 'A';
// Now add the key
const int shifted = normalized + key;
// Addition result maybe bigger then 25, so overflow. Cap it
const int capped = shifted % 26;
// Get back a character
const char convertedUppcase = (char)capped + 'A';
// And set back the original case
result = originalIsLower ? (char)std::tolower(convertedUppcase) : convertedUppcase;
}
return result;
};
std::transform(in.begin(), in.end(), res.begin(), convert);
return res;
}
And if you want to see a solution with only the simplest statements, then see the below.
#include <iostream>
#include <string>
using namespace std;
string caesar(string in, int key) {
// Here we will store the resulting encrypted/decrypted string
string result{};
// Handling of a negative key (Shift to left). Key will be converted to positive value
if (key < 0) {
// limit the key to 0,-1,...,-25
key = key % 26;
// Key was negative: Now we have someting between 0 and 26
key = 26 + key;
};
// Read character by character from the string
for (unsigned int i = 0; i < in.length(); ++i) {
char c = in[i];
// CHeck for alpha character
if ((c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z')) {
// Check and remember if the original character was lower case
bool originalIsLower = (c >= 'a' and c <= 'z');
// We want to work with uppercase only
char upperCaseChar = originalIsLower ? c - ('a' - 'A') : c;
// But, we want to start with 0 and not with 'A' (65)
int normalized = upperCaseChar - 'A';
// Now add the key
int shifted = normalized + key;
// Addition result maybe bigger then 25, so overflow. Cap it
int capped = shifted % 26;
// Get back a character
char convertedUppcase = (char)capped + 'A';
// And set back the original case
result += originalIsLower ? convertedUppcase + ('a' - 'A') : convertedUppcase;
}
else
result += c;
}
return result;
}
int main() {
string test{ "aBcDeF xYzZ" };
string encrypted = caesar(test, 5);
string decrypted = caesar(encrypted, -5);
cout << "Original: " << test << '\n';
cout << "Encrpyted: " << encrypted << '\n';
cout << "Decrpyted: " << decrypted << '\n';
}
I am having issue to understand this code. The goal is to add the sum of all digit from a number until there is only 1 digit recursively
long long superDigit(string n, int k) {
if (n.size() == 1)
return stoi(n);
long long sum = 0;
for (int i = 0 ; i < n.size() ; i++)
sum += (n[i] - '0') * k;
return superDigit(to_string(sum),1);
}
However, i don't understand this line
sum += (n[i] - '0') * k;
n is a string k is an integer what to expect from this kind of multiplication ?
Moreover i tested the operator - on string and i don't get how it works.
Every character has a numerical value. You can find these values on the ASCII Table. The characters 0-9 are placed in a contiguous chunk on the ASCII table, with 0 at 48 and 9 and 57. So, when you do a char minus '0', you get how far away it is from '0' on the ASCII table, effectively converting the character to its corresponding number. '0' - '0' is 0 since they're the same character, '1' - '0' is 1 since 1 is right next to 0 (49 - 48), '2' - '0' is 2 since it's 2 away (50 - 48 = 2), and so on.
I'm new in arduino programming (c/c+). And would like to convert a array with bool's to an byte like. The booleans repreprents a buttons here.
bool array[] = {0,1,1,0}; // needs to convert to 0b0110
// bool array[] = {1,0,0,0}; // needs to convert to 0b1000
// bool array[] = {true,true,false,true}; // needs to convert to 0b1101
void setup(){
byte b = convert(array); // 0b0110
}
byte convert(bool array[]){
byte b = 0b + 0 + 1 + 1 + 0; // <- wrong stuff here :(
return b;
}
I can't rewrite all your code right now, but I can lay out a basic algorithm. I think it'll help you.
You need something, either in a loop or hardcoded (if you really only have four bits). For brevity, I'm going to call your array a and I'll just hardcode the calculation so it's super-clear.
If you think of the entries of your array in bits, it's like this:
eights fours twos ones
{ 0 , 1 , 1 , 0 }
You get these values by using the left-shift operator << which doubles the value for each shift.
So with the leftmost member of your array as the most significant bit, you do it like this:
shift 3 shift 2 shift 1 no shift
uint8_t b = (a[0] << 3) + (a[1] << 2) + (a[2] << 1) + a[3];
so -> no eights one four one two no ones
6 = 0 + 4 + 1 + 0
Do you see the pattern? Each less significant bit is shifted by one LESS to the left, halving its total value. The sum of these values is your byte value (uint8_t).
There are other notations which have the same effect, but this one is the easiest to understand.
Now to the booleans. You could use the ternary operator and test each element, something like this:
uint8_t b = (
(a[0] ? 1 << 3 : 0) +
(a[1] ? 1 << 2 : 0) +
(a[2] ? 1 << 1 : 0) +
(a[3] ? 1 : 0 )
);
Once you see this pattern, you can do all sorts of cool bitwise constructions with it.
I referred a program for time conversion and not able to understand some part of the code. Here's the full program.
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.length();
int hh, mm, ss;
hh = (s[0] - '0') * 10 + (s[1] - '0');
mm = (s[3] - '0') * 10 + (s[4] - '0');
ss = (s[6] - '0') * 10 + (s[7] - '0');
if (hh < 12 && s[8] == 'P') hh += 12;
if (hh == 12 && s[8] == 'A') hh = 0;
printf("%02d:%02d:%02d\n", hh, mm, ss);
return 0;
}
The part of code i am not able to understand is
hh = (s[0] - '0') * 10 + (s[1] - '0');
mm = (s[3] - '0') * 10 + (s[4] - '0');
ss = (s[6] - '0') * 10 + (s[7] - '0');
Thanks in advance.
If you see e.g. this ASCII table (ASCII being the most common character encoding scheme) you can see that the character '2' has the decimal value 50, and that the character '0' has the decimal value 48.
Considering that a character is just really a small integer, we can use normal arithmetic on them. That means if you do e.g. '2' - '0' that's the same as doing 50 - 48 which results in the decimal value 2.
So to get the decimal value of a character digit, just subtract '0'.
The multiplication with 10 is because we're dealing with the decimal system, where a number such as 21 is the same as 2 * 10 + 1.
It should be noted that the C++ specification explicitly says that all digits have to be encoded in a contiguous range, so it doesn't matter which encoding is used this will always work.
You might see this "trick" being used to get a decimal value for letters as well, but note that the C++ specification doesn't say anything about that. In fact there are encodings where the range of letters is not contiguous and where this will not work. It's only specified to work on digits.
In the ASCCI encoding numbers are encoded sequentially. This is:
'0' has the value 48
'1' has the value 49
'2' has the value 50
etc
Therefor, 'x' - '0' == x from '0' to '9'
For example:
if you have your string 12:23:53 we have:
hh = (s[0] - '0') * 10 + (s[1] - '0');
(s[0] - '0') means '1'-'0' which is equal to 1, but this is the ten, so *10 + (s[1] - '0') which is '2'-'0', so 2. In total 12.
Same thing for the minutes and seconds.
i have a byte array. Now i need to know the count of appearances of a bit pattern which length is N.
For example, my byte array is "00100100 10010010" and the pattern is "001". here N=3, and the count is 5.
Dealing with bits is always my weak side.
You could always XOR the first N bits and if you get 0 as a result you have a match. Then shift the searched bit "stream" one bit to the left and repeat. That is assuming you want to get matches if those sub-patterns overlap. Otherwise you should shift by pattern length on match.
If N may be arbitrary large You can store the bit pattern in a vector
vector<unsigned char> pattern;
The size of the vector should be
(N + 7) / 8
Store the pattern shifted to the right. By this, I mean, that for example, if N == 19, Your vector should look like:
|<- v[0] ->|<- v[1] ->|<- v[2] ->|
0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1
| |<- pattern ->|
If You have Your pattern originally shifted to the left, You can use the function I'll present below, to shift the bits to the right.
Define a vector of bytes, of the same length as the pattern, to store a part of Your bit stream for comparing it with the pattern. I'll call it window
vector<unsigned char> window;
If N is not an integer multiple of 8, You will need to mask some leftmost bits in Your window, when comparing it with the pattern. You can define the mask this way:
unsigned char mask = (1 << (N % 8)) - 1;
Now, assuming the window contains the bits, it should, You could theoretically compare the pattern with the window using vector's operator == like this
window[0] &= mask;
bool isMatch = (window == pattern);
But there are good reasons to be a little bit more sophisticated. If N is large and Your byte array, You look for the pattern in, is significantly larger, it's worth it, to process the pattern and build a vector of size N+1:
vector<int> shifts;
This vector will store the information, how many bits to shift the bit stream by, for the next comparison, based on the position, at which there is a mismatch in the current window.
Consider the pattern 0001001100. You should compare the bits with the window from right to left. If there is a missmatch at the first bit, You know it's 1 and the first occurrence of 1 in Your pattern is at the position 2 counting form 0 form the right to the left. So in that case, You know, that it doesn't make sense to make a comparison if the number of new bits shifted form the bit stream into the window is less than 2. Similarly if the mismatch occurs at the third bit (position 2 counting form 0), the window should be moved by 7, because 3 consecutive zeros in your pattern are at the end. If the mismatch is at the position 4, You can move the window by 8 and so on. The sifts vector, at an index i will hold number of bits, by which to move the window, if the mismatch occurs at the position i. If there is a match, the window should be moved by the number of bits stored in shifts[N]. In the example above, a match means a shift by 8.
In practice of course, You compare whole bytes form the pattern with the bytes from the window (going form right to left) and if there is a mismatch You examine the bits in the byte to find the mismatch position.
if(window[i] != pattern[i])
{
int j = 0;
unsigned char mismatches = window[i] ^ pattern[i];
while((mismatches & 1) == 0)
{
mismatches >>= 1;
++j;
}
mismatch_position = 8 * (window.size() - i - 1) + j;
}
Here is a function that might come handy, when You need to shift some bits from Your bit stream into the window. I wrote it in C#, but conversion to C++ should be trivial. C# makes some casts necessary, that are probably not necessary in C++. Use unsigned char instead of byte, vector<unsigned char> & instead of byte [], size() instead of Length and maybe some more minor tweaks. The function is probably a little more general than needed in Your scenario, as it doesn't use the fact, that consecutive calls retrieve consecutive chunks of Your byte array, which maybe could make it a bit simpler, but I don't think it hurts. In the current form, it can retrieve arbitrary bit substring form the byte array.
public static void shiftBitsIntoWindow_MSbFirst(byte[] window, byte[] source,
int startBitPosition, int numberOfBits)
{
int nob = numberOfBits / 8;
// number of full bytes from the source
int ntsh = numberOfBits % 8;
// number of bits, by which to shift the left part of the window,
// in the case, when numberOfBits is not an integer multiple of 8
int nfstbb = (8 - startBitPosition % 8);
// number Of bits from the start to the first byte boundary
// The value is from the range [1, 8], which comes handy,
// when checking if the substring of ntsh first bits
// crosses the byte boundary in the source, by evaluating
// the expression ntsh <= nfstbb.
int nfbbte = (startBitPosition + numberOfBits) % 8;
// number of bits from the last byte boundary to the end
int sbtci;
// index of the first byte in the source, from which to start
// copying nob bytes from the source
// The way in which the (sbtci) index is calculated depends on,
// whether nob < window.Length
if(nob < window.Length)// part of the window will be replaced
// with bits from the source, but some part will remain in the
// window, only moved to the beginning and possibly shifted
{
sbtci = (startBitPosition + ntsh) / 8;
//Loop below moves bits form the end of the window to the front
//making room for new bits that will come form the source
// In the corner case, when the number by which to shift (ntsh)
// is zero the expression (window[i + nob + 1] >> (8 - ntsh)) is
// zero and the loop just moves whole bytes
for(int i = 0; i < window.Length - nob - 1; ++i)
{
window[i] = (byte)((window[i + nob] << ntsh)
| (window[i + nob + 1] >> (8 - ntsh)));
}
// At this point, the left part of the window contains all the
// bytes that could be constructed solely from the bytes
// contained in the right part of the window. Next byte in the
// window may contain bits from up to 3 different bytes. One byte
// form the right edge of the window and one or two bytes form
// the source. If the substring of ntsh first bits crosses the
// byte boundary in the source it's two.
int si = startBitPosition / 8; // index of the byte in the source
// where the bit stream starts
byte byteSecondPart; // Temporary variable to store the bits,
// that come from the source, to combine them later with the bits
// form the right edge of the window
int mask = (1 << ntsh) - 1;
// the mask of the form 0 0 1 1 1 1 1 1
// |<- ntsh ->|
if(ntsh <= nfstbb)// the substring of ntsh first bits
// doesn't cross the byte boundary in the source
{
byteSecondPart = (byte)((source[si] >> (nfstbb - ntsh)) & mask);
}
else// the substring of ntsh first bits crosses the byte boundary
// in the source
{
byteSecondPart = (byte)(((source[si] << (ntsh - nfstbb))
| (source[si + 1] >> (8 - ntsh + nfstbb))) & mask);
}
// The bits that go into one byte, but come form two sources
// -the right edge of the window and the source, are combined below
window[window.Length - nob - 1] = (byte)((window[window.Length - 1] << ntsh)
| byteSecondPart);
// At this point nob whole bytes in the window need to be filled
// with remaining bits form the source. It's done by a common loop
// for both cases (nob < window.Length) and (nob >= window.Length)
}
else// !(nob < window.Length) - all bits of the window will be replaced
// with the bits from the source. In this case, only the appropriate
// variables are set and the copying is done by the loop common for both
// cases
{
sbtci = (startBitPosition + numberOfBits) / 8 - window.Length;
nob = window.Length;
}
if(nfbbte > 0)// The bit substring coppied into one byte in the
// window crosses byte boundary in the source, so it has to be
// combined form the bits, commming form two consecutive bytes
// in the source
{
for(int i = 0; i < nob; ++i)
{
window[window.Length - nob + i] = (byte)((source[sbtci + i] << nfbbte)
| (source[sbtci + 1 + i] >> (8 - nfbbte)));
}
}
else// The bit substring coppied into one byte in the window
// doesn't cross byte boundary in the source, so whole bytes
// are simply coppied
{
for(int i = 0; i < nob; ++i)
{
window[window.Length - nob + i] = source[sbtci + i];
}
}
}
Assuming your array fits into an unsigned int:
int main () {
unsigned int curnum;
unsigned int num = 0x2492;
unsigned int pattern = 0x1;
unsigned int i;
unsigned int mask = 0;
unsigned int n = 3;
unsigned int count = 0;
for (i = 0; i < n; i++) {
mask |= 1 << i;
}
for (i = 8 * sizeof(num) - n; i >= 0; i--) {
curnum = (num >> i) & mask;
if (! (curnum ^ pattern)) {
count++;
}
}
}
Convert your byte array and pattern each to a std::vector<bool>, then call std::search(source.begin(), source.end(), pattern.begin(), pattern.end());. Despite vector<bool>s idiosyncracies, this will work.