Okay, here's your solution (it's not very thoroughly tested though):
template<typename TItem, typename TItem2>
void SetEnableFlags(TItem &BitFlags, const TItem2 &Flags)
{
BitFlags = (BitFlags|Flags);
}
const unsigned char CharArrayToByte(const char Data[])
{
if(Data == NULL){return 0;}
if(strlen(Data) < 8){return 0;}
unsigned char Byte = 0;
SetEnableFlags(Byte,(Data[0]-'0')*128);
SetEnableFlags(Byte,(Data[1]-'0')*64);
SetEnableFlags(Byte,(Data[2]-'0')*32);
SetEnableFlags(Byte,(Data[3]-'0')*16);
SetEnableFlags(Byte,(Data[4]-'0')*8);
SetEnableFlags(Byte,(Data[5]-'0')*4);
SetEnableFlags(Byte,(Data[6]-'0')*2);
SetEnableFlags(Byte,(Data[7]-'0')*1);
return Byte;
}
const bool ConvertToBytes(char Bytes[], const char Binary[])
{
if( (Binary == NULL) || (Bytes == NULL) ){return false;}
//Checks it's a power of 8
int Size = strlen(Binary);
if(Size < 8){return false;}
float SizeTest = ((float)Size/8.0);
if( (SizeTest - (int)SizeTest ) != 0.0 ){return false;}
unsigned int Power = 0;
unsigned int Iter = 0;
do
{
Power = 8*Iter;
Bytes[Iter] = CharArrayToByte( (Binary+Power) );
Iter++;
}while(Power < Size);
return true;
}
int main()
{
char Bytes[3]; //Allocate enough space for it
char Binary[] = "000000010000001100001111"; //1, 3, 15
if(!ConvertToBytes(Bytes,Binary)){return 1;}
printf("%d %d %d!\n",Bytes[0],Bytes[1],Bytes[2]);
return 0;
}
You may want to consider also reading this thread here to make your job easier.
The code isn't optimised. You can use it for whatever purpose, even commercial (if you're able to sell it). Strings will get unreadable beyond 8 bits, so you may just wish to call CharArrayToByte manually (ensure the char array length is indeed 8 characters or you will have issues). If you want to convert it back, it's a matter of reversing the process.
It wasn't clear whether you were using C or C++ (with C coding), so you'll likely have to modify it to suit your needs.