Home > Blockchain >  vector data loss when exiting a loop
vector data loss when exiting a loop

Time:11-30

i did a very basic and small function to convert a number smaller than 256 to binary

void convertToBinary(short decimalNumber, vector<short> &binaryNumber)
{
    short divisor = 128;
    while (decimalNumber != 0)
    {
        short divised = decimalNumber/divisor; // 1
        binaryNumber.push_back(divised);
        if (decimalNumber > divisor)
        {
            decimalNumber -= divisor;
        }
        divisor /= 2;
    }
}

but when i try to get the result it always happens to be empty

short decimalNumber = 231; //random number
vector<short> binaryNumber;
convertToBinary(decimalNumber, binaryNumber);
for (int i = 0; i < size(binaryNumber); i  )
{
    cout << binaryNumber[i];
}

i think i messed up with pointers, but i dont know how to make it work

CodePudding user response:

you end up with divisor = 0

this works fine

while (decimalNumber != 0 && divisor > 0)
  • Related