How to print bits in c

前端 未结 5 1137
礼貌的吻别
礼貌的吻别 2021-01-21 10:30

I\'m writing a function to print bits in c, I\'m only allowed to use write function. my function doesn\'t work for other numbers.

void    print_bit         


        
5条回答
  •  一整个雨季
    2021-01-21 11:16

    Including limits.h for CHAR_BIT, allows you to generalize the funciton to allow passing values of any length but limiting the the output to the number of bytes desired. Passing the file descriptor will allow writing to any open descriptor (or simply passing STDOUT_FILENO to write to stdout.

    void writebits (const unsigned long v, int fd)
    {
        if (!v)  { putchar ('0'); return; };
    
        size_t sz = sizeof v * CHAR_BIT;
        unsigned long rem = 0;
    
        while (sz--)
            if ((rem = v >> sz))
                write (fd, (rem & 1) ? "1" : "0", 1);
    }
    

    For example:

    #include 
    #include 
    
    /* CHAR_BIT */
    #ifndef CHAR_BIT
    # define CHAR_BIT  8
    #endif
    
    void writebits (const unsigned long v, int fd)
    {
        if (!v)  { putchar ('0'); return; };
    
        size_t sz = sizeof v * CHAR_BIT;
        unsigned long rem = 0;
    
        while (sz--)
            if ((rem = v >> sz))
                write (fd, (rem & 1) ? "1" : "0", 1);
    }
    
    int main (void) {
    
        unsigned v = 0xcafebabe;
    
        writebits (v, STDOUT_FILENO);
        putchar ('\n');
        writebits ((unsigned char)(v >> 24), STDOUT_FILENO);
        putchar ('\n');
    
        return 0;
    }
    

    Example Output

    $ ./bin/writebits
    11001010111111101011101010111110
    11001010
    

提交回复
热议问题