Hello,

Been struggling with this for a while now.

I'm trying to create a function like:

unsigned int setDigit(unsigned int inputNumber, byte newDigit, byte loc, byte exponent)

It should basically accept an unsigned int, a byte, a location and the exponent. It should then update whatever number is at location loc to the newDigit byte that's passed in.

I'm using this on a display 4x7 segment display that will show a number either in dec or hex (hence the exponent parameter) and the user can change a single digit that's being displayed by pressing a button to move the "cursor" left or right, and then press a number on a keypad to set that digit.

I do have a semi working version of this code, but having problems dealing with the edge cases. For example, when the address is 0 all my logic fails.

I've tried breaking the number up into a string and setting the index to the passed byte, but this also fails.

Here are my 2 attempts at it:

Non-string version:

unsigned int setDigit(unsigned int inputNumber, byte newDigit, byte loc, byte exponent) {

const byte maxSize = 32;

byte numberSize = (inputNumber == 0 ? 1 : 0);

unsigned int nSize = inputNumber;

while (nSize != 0 && numberSize < maxSize) {

nSize /= exponent;

numberSize++;

}

if (loc > maxSize || loc > numberSize || loc < 0) {

return inputNumber;

}

char *numberArray = calloc((int)numberSize, sizeof(char));

unsigned int i = 0;

unsigned int nCount = inputNumber;

while (nCount != 0 && i < numberSize) {

numberArray[i] = nCount % exponent;

nCount /= exponent;

i++;

};

numberArray[loc] = (newDigit % exponent);

int output = 0;

for (byte j = 0; j < numberSize; j++) {

output = exponent * output + numberArray[j];

}

if (numberArray) {

free(numberArray);

}

return output;

}

String version:

unsigned int setDigit(unsigned int inputNumber, byte newDigit, byte loc, byte exponent) {

const byte maxSize = 32;

String inputString = "";

if (loc > maxSize || loc < 0) {

if (SERIAL_ERRORS && Serial) {

Serial.print("\nsetDigit(): Error: Index out of bounds.\n");

}

return inputNumber;

}

char temp[maxSize] = {0};

sprintf(temp, "%d", inputNumber);

inputString.concat(temp);

char replaceNum[maxSize] = {0};

sprintf(replaceNum, "%01d", (newDigit % exponent));

inputString[loc] = replaceNum;

unsigned int output = 0;

output = strtol(inputString.c_str(), NULL, exponent + 1);

return output;

}