/* CODE and DECODE DEC to BIN value
* Save space to use 8 position ON/OFF in dec value 0-255
* in arduino EEPROM
*/
void setup() {
Serial.begin(9600);
Serial.println( "Begin" );
}
unsigned decNum = 20;
void loop() {
for (int pos=1; pos<=8; pos++){
Serial.print( decNum );
Serial.print( " ");
Serial.print("SET 1 ");
Serial.print(" to ");
Serial.print(pos);
Serial.print(" pos DECVAL:");
decNum = setBoolValueToDec(decNum, pos, 1 );
Serial.println(decNum);
}
//set 0/1 to position in present DECNUM and return new DECNUM
delay(3000);
}
// Set value 0/1 to position and return DEC 0-255 for save to memory
unsigned int setBoolValueToDec(int inDecNum, int pos, bool val ){
String myStr, newStr;
long binValue = dec2bin(inDecNum);
myStr = String(binValue);
//fillout short string to 8 position
while(myStr.length() < 8){
myStr="0"+myStr;
}
Serial.print(myStr);
Serial.print(" - ");
for (int i=7;i>=0;i--){
if (8-pos == i){
newStr = val + newStr;
}else{
newStr = myStr.charAt(i) + newStr;
}
}
Serial.print(newStr);
Serial.print(" - ");
//int dec_ = 0;
//dec_ = (int) newStr.toInt();
//return bin2dec(dec_);
//int getDecimalValue(bits){
}
int getDecimalValue(bits){
int ret = 0;
int base = 1;
for(int i = 7; i >= 0; i--){
ret += bits[i] * base;
base = base * 2;
}
return ret;
}
//vrati hodnotu z binarni pozice
// 255 - 11111111 read from right to left
bool getValueFromDec(int decNum, byte pos){
String myStr, valRes;
//String binValue = String(decNum, BIN);
long binValue = dec2bin(decNum);
myStr = String(binValue);
int strLen = myStr.length();
int charPos = strLen-pos;
valRes = myStr.charAt(charPos);
if (valRes.toInt() == 1)
return true;
return false;
}
//decimal to binary
long dec2bin (int dec){
int reminder;
String bin;
while (dec) {
reminder = dec % 2;
dec = dec / 2;
bin = String(reminder) + bin;
}
return bin.toInt();
}
//binary to DEC
long bin2dec(long binary) {
long number = binary;
long decimalVal = 0;
long baseVal = 1;
long tempVal = number;
long previousDigit;
while (tempVal) {
//Converts Binary to Decimal
previousDigit = tempVal % 10;
tempVal = tempVal / 10;
decimalVal += previousDigit * baseVal;
baseVal = baseVal * 2;
}
//Returns the Decimal number
return decimalVal;
}