-1
//------------------------------------------------------------------------------------------//
//  divisionAlg -- This will take the incoming value and "asciify" each byte according to
//                 a character lookup table
//
//  Parameters:
//      unsigned int value -- the value to be asciified
//
//------------------------------------------------------------------------------------------//

void divisionAlg(unsigned int value);

int main(int argc, char *argv[])        // Always remember to pass an argument while executing
{
 divisionAlg(45);
}

void divisionAlg(unsigned int value)
{
    int MAX_REM=2;
    int MAX_BASE=10;
    const char *charTable = {"0123456789ABCDEF"};  // lookup table for converting remainders
    char rembuf[MAX_REM + 1];   // holds remainder(s) and provision null at the end
    int  index;                 // 
    int  i;                     // loop variable

    unsigned int rem;           // remainder
    unsigned int base;          // we'll be using base 10 
    ssize_t numWritten;         // holds number of bytes written from write() system call

    base = 10;

    // validate base
    if (base < 2 || base > MAX_BASE)
        err_sys("oops, the base is wrong");

    // For some reason, every time this method is called after the initial call, rembuf
    // is magically filled with a bunch of garbage; this just sets everything to null.
    // NOTE: memset() wasn't working either, so I have to use a stupid for-loop
    for (i=0; i<MAX_REM; i++)
        rembuf[i] = '\0';

    rembuf[MAX_REM] = 0;    // set last element to zero
    index = MAX_REM;        // start at the end of rembuf when adding in the remainders

    do
    {
        // calculate remainder and divide valueBuff by the base
        rem = value % base;
        value /= base;

        // convert remainder into ASCII value via lookup table and store in buffer
        index--;
        rembuf[index] = charTable[rem];

    } while (value != 0);

    // display value
    if ((numWritten = write(STDOUT_FILENO, rembuf, MAX_REM + 1)) == -1)
        err_sys("something went wrong with the write");

} // end of divisionAlg()

我正在尝试制作除法算法,但我不知道为什么不起作用,请帮助!

这个“除法算法”被假定为获取传入的值并根据字符查找表“asciify”每个字节

4

1 回答 1

0

我认为这就是为什么:

首先将整个数组(长度为 MAX_REM+1,例如 0 到 MAX_REM 是有效索引)初始化为空值 (0x00)。所以 rembuf 看起来像这样(0x00 为 ascii null):

'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', ... '0x00', '0x00', '0x00', '0x00'

现在,我们通过这样做将值插入到 rembuf 中:

index = MAX_REM;
index--;
rembuf[index] = charTable[rem];

所以在循环结束时,如果我们在 12 上运行你的算法,我们可能会得到这样的结果:

'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', ... '0x00', '1', '2', '0x00'

现在打印你这样做:

if ((numWritten = write(STDOUT_FILENO, rembuf, MAX_REM + 1)) == -1)

问题是你把它传递给了rembuf。当它从 rembuf 读取时,它立即看到 0x00 并决定“这个字符串是空的,我无事可做”。您实际上应该做的是向它传递一个指向您的号码开始位置的指针 - '1' 在内存中的位置。(编辑:正如评论所说,write()写入尽可能多的字节,并且不会在空值上停止,所以这不是原因)

编辑:当您使用它时,MAX_REM 应该大得多(对于将 2^32 作为字符串保存的情况,它需要为 10 - 对于 2^64,它需要为 20)

于 2013-01-30T23:51:50.507 回答