• Status: Solved
• Priority: Medium
• Security: Public
• Views: 459
• Last Modified:

C++, how to find a character's matching index within another character array?

Hi all,

I have a character array with base 64 digits "alph" and I have a character array containing a base 64 message, "cTotalImage". My algorithm below works fine, but I was thinking that there MUST be a better way to find a particular character's index within "alph". Does anyone know of a faster general approach to what I'm doing here?

Please let me know if I can clear any of this up! Thanks for your help in advance.

BTW I know there are classes out there that do this, but I'd rather write one of my own so that I can learn and grow my programming knowledge - do not suggest that I go elsewhere for a base 64 decoding class.
``````char alph[64];
strcpy(alph, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");

// Find index of characters in alph
short iSearch;
short iDecimals[4] = {0, 0, 0, 0};
for (iSearch = 0; iSearch < 64; iSearch++)
{
if (cTotalImage[iDecodeIndex] == alph[iSearch])
{
iDecimals[0] = iSearch;
break;
}
}
for (iSearch = 0; iSearch < 64; iSearch++)
{
if (cTotalImage[iDecodeIndex + 1] == alph[iSearch])
{
iDecimals[1] = iSearch;
break;
}
}
// etc...
``````
0
ehensens
Asked:
• 2
1 Solution

Commented:
// if you are going to do it many times, initialize
int index[CHAR_MAX+1];

for( int i;i<64;i++){
index[alpha[i] = i;
}

then

for( i=0;i<4; i++ ){
decimals[i] = index[cTotalImage[iDecodeIndex+i]];
}
0

Author Commented:
Hi ozo,

Thank you for your reponse. I cannot quite understand what you're doing (sorry), could you please add comments and fix the index[alpha[i] = i; part? Thanks!
0

Commented:
You can calculate the index if you take into accout that the alphabet is consecutive and the ASCII characters are also, e.g.
``````#include <ctype.h>

// ...

if (isupper(cTotalImage[iDecodeIndex]) { // uppercase character

iDecimals[0] = cTotalImage[iDecodeIndex] - 65; // ASCII 'A' == 65
}

if (islower(cTotalImage[iDecodeIndex]) { // lowercase character

iDecimals[0] = cTotalImage[iDecodeIndex] - 97 + 25; // ASCII 'a' == 97, add offset until 'Z' in your array
}

if (isdigit(cTotalImage[iDecodeIndex]) { // 0 - 9

iDecimals[0] = cTotalImage[iDecodeIndex] - 48 + 50; // ASCII '0' == 97, add offset until 'z' in your array
}

// add special treatment for +/
``````
0

Author Commented:
I like this approach, good thinking.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.