Thread: void showbits(int) Definition

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    51

    void showbits(int) Definition

    k = n & andmask; How to determine its result?
    Code:
    #include <stdio.h>
    void showbits(int);
    int main()
    {
        int j,k;
        for(j=0;j<=15;j++)
        {
            printf("\nBinary value of decimal %d is :",j);
            showbits(j);
    
    
        }
        return 0;
    }
    void showbits(int n){
        int i,k,andmask;
        for(i = 15;i>=0;i--){
            andmask = 1<<i;
            k = n & andmask;
            k==0 ? printf("0"):printf("1");
        }
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,558
    Read up on bitwise operators.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2019
    Posts
    51
    Quote Originally Posted by laserlight View Post
    Read up on bitwise operators.
    Yup but I am not being able to understand that what is ANDMask and why do we need to find an AND MASK and how to find ADD MASK? Further n and andmask both are operands with 32 bits. k will be 0 or 1 how can we conclude it in this statement; k = n & andmask;

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,558
    Quote Originally Posted by rm82co
    what is ANDMask
    A bit mask, i.e., a sequence of bits used to toggle specific bits in another sequence of bits.

    Quote Originally Posted by rm82co
    why do we need to find an AND MASK
    So that we can turn off (unset, set to zero) all the bits except the one we want to examine on that iteration.

    Quote Originally Posted by rm82co
    k will be 0 or 1
    No, k will be 0 or an integral power of 2.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    647
    @rm84co, a mask is an object people use to hide parts of their faces (or all of it). By analogy, a bit mask is a set of bits used to hide (or change) another set of bits.

    When you use AND operation, if one of the operands is 1, the result will be the other operand... Example: 1 and 0 = 0, 1 and 1 = 1.
    If one of the operands is 0, the result is always zero: 0 and 0 = 0, 0 and 1 = 0... So bit bit is masked.

    You can use AND to isolate individual bits. for instance, if I want to know only the value of bit 0, masking all the other bits, I can do:
    Code:
    y = 1 & x;
    Here, y will have all its bits zeroed, except bit 0. Bit 0 will be a copy of x's bit 0.

    If you want to mask all the bits, except bit 2, for example, you can do:

    Code:
    y = 4 & x;
    Because 4 is 0b000...00000100. The mask has only bit 2 set... To simplify you can do something like this:

    Code:
    y = (1 << 2) & x;
    The (1 << 2) will set the appropriate bit and it is a constant.

    Knowing this you could write a code like this to show all the bits, individually, of an integer:
    Code:
    void show_int_bits( int x )
    {
      // We'll print all bits of x.
      unsigned int bit_count = 8 * sizeof x;
    
      // will mask all bits, except the highest.
      unsigned int bit_mask = 1U << (sizeof(int)*8 - 1);
    
      while ( bit_count-- )
      {
        // (x & bit_mask) will be 0 if higherst bit of x is 0
        // or will be different from 0 if highest bit of x is 1.
        putchar( x & bit_mask ? '1' : '0' );
    
        // shift all bits to the left, 1 step.
        x <<= 1;
      }
    
    }
    Got it?
    Last edited by flp1969; 04-04-2019 at 06:51 PM.

  6. #6
    Registered User
    Join Date
    Mar 2019
    Posts
    51
    Quote Originally Posted by flp1969 View Post
    @rm84co, a mask is an object people use to hide parts of their faces (or all of it). By analogy, a bit mask is a set of bits used to hide (or change) another set of bits.

    When you use AND operation, if one of the operands is 1, the result will be the other operand... Example: 1 and 0 = 0, 1 and 1 = 1.
    If one of the operands is 0, the result is always zero: 0 and 0 = 0, 0 and 1 = 0... So bit bit is masked.

    You can use AND to isolate individual bits. for instance, if I want to know only the value of bit 0, masking all the other bits, I can do:
    Code:
    y = 1 & x;
    Here, y will have all its bits zeroed, except bit 0. Bit 0 will be a copy of x's bit 0.

    If you want to mask all the bits, except bit 2, for example, you can do:

    Code:
    y = 4 & x;
    Because 4 is 0b000...00000100. The mask has only bit 2 set... To simplify you can do something like this:

    Code:
    y = (1 << 2) & x;
    The (1 << 2) will set the appropriate bit and it is a constant.

    Knowing this you could write a code like this to show all the bits, individually, of an integer:
    Code:
    void show_int_bits( int x )
    {
      // We'll print all bits of x.
      unsigned int bit_count = 8 * sizeof x;
    
      // will mask all bits, except the highest.
      unsigned int bit_mask = 1U << (sizeof(int)*8 - 1);
    
      while ( bit_count-- )
      {
        // (x & bit_mask) will be 0 if higherst bit of x is 0
        // or will be different from 0 if highest bit of x is 1.
        putchar( x & bit_mask ? '1' : '0' );
    
        // shift all bits to the left, 1 step.
        x <<= 1;
      }
    
    }
    Got it?
    I could understand this and doing like this.
    Code:
    #include<stdio.h>
    #include<conio.h>
    
    
    #ifdef SHOWBITS
    
    
    void showbits(int);
    int main(void)
    {
    	int j;
    	for(j =0 ; j <= 15; j++)
    	{
    		printf("\nInteger %d Binary", j);
    		showbits(j);	
    	}
    	system("pause");
    }
    #else
    
    
    #include <stdio.h>
    void showbits(int);
    int main()
    {
        int j,k;
        for(j=0;j<=15;j++)
        {
            printf("\nBinary value of decimal %d is :",j);
            showbits(j);
    
    
        }
        return 0;
    }
    void showbits(int n){
        
    	int i, k, bit;
        for(i = ((sizeof(int)*8) - 1); i >= 0; i-- ){
            k = n >> i; 						// mask: move required bit to bit number 0 position
            bit = k & 1;						// bit: k & 1, one will make left bits of the bit required to isolate, 0 because 00000...0001(32 bits total)
            bit==0 ? printf("0"):printf("1");
        }
    }
    #endif

  7. #7
    Registered User
    Join Date
    Feb 2019
    Posts
    647
    Yes, your showbits() is correct too. There is a small thing you should pay attention using right shifts on signed integer types: There is 2 types of right shifts: arithmetic and logical. Probably the compiler will use the arithmetic kind, but the standard says this is "implementation defined". In your routine this doesn't matter, since you are masking all bits except bit 0, after the shift.

    The difference between my implementation and yours is that I prefer to mask all but the most significant bit, shifting left 1 bit per loop iteration, because I learned to avoid that "implementation defined" behavior, for the sake of portability (that's why I use sizeof(int)*8 and 8*sizeof x to get bit counts. I could use the constant 32).

    This is not a criticism, as I said, your routine is correct! But mine, on x86-64, is a little better (side by side listing in assembly):

    Code:
    showbits_rm82co:          showbits_fred:
        push  rbp                 push   rbp
        push  rbx                 push   rbx
        mov   ebp, edi            mov    ebp, edi
        mov   ebx, 31             mov    ebx, 32
        sub   rsp, 8              sub    rsp, 8
        jmp   .L4             .L12:
    .L9:                          mov    edi, ebp
        mov   edi, '0'            mov    rsi, QWORD [rip+stdout]
        sub   ebx, 1              add    ebp, ebp
        call  putchar@PLT         shr    edi, 31
        cmp   ebx, -1             add    edi, '0'
        je    .L8                 call   _IO_putc@PLT
    .L4:                          sub    ebx, 1
        bt    ebp, ebx            jne    .L12
        jnc   .L9                 add    rsp, 8
        mov   edi, '1'            pop    rbx
        sub   ebx, 1              pop    rbp
        call  putchar@PLT         ret
        cmp   ebx, -1
        jne   .L4
    .L8:
        add   rsp, 8
        pop   rbx
        pop   rbp
        ret
    Notice, in my routine, there is only one call to _IO_putc (more efficient than putchar) and less jumps... You can archive the same result making this change:
    Code:
    // bit == 0 ? printf("0") : printf("1");
    putchar( bit == 0 ? '0' : '1' );
    PS: YOUR routine is way more efficient than mine on ARM!

    Code:
    showbits_rm82co:               showbits_fred:           
      push  {r4, r5, r6, lr}         push  {r4, r5, r6, lr}
      mov r5, r0                     mov r5, r0
      mov r4, #31                    ldr r6, .L19
    .L4:                             mov r4, #32
      asr r3, r5, r4                 b .L14
      mov r0, #48                  .L11:
      tst r3, #1                     ldr r3, [r2]
      movne r0, #49                  subs  r4, r4, #1
      bl  putchar                    lsl r5, r5, #1
      subs  r4, r4, #1               add r0, r3, #1
      bcs .L4                        str r0, [r2]
      pop {r4, r5, r6, lr}           strb  r1, [r3]
      bx  lr                         beq .L18
                                   .L14:
                                     ldr r0, [r6]
                                     cmp r5, #0
                                     movlt r1, #49
                                     movge r1, #48
                                     ldr r2, [r0, #8]
                                     ldr r3, [r2, #8]
                                     sub r3, r3, #1
                                     cmp r3, #0
                                     str r3, [r2, #8]
                                     bge .L11
                                     ldr ip, [r2, #24]
                                     cmp r3, ip
                                     bge .L11
                                     bl  __swbuf_r
                                     subs  r4, r4, #1
                                     lsl r5, r5, #1
                                     bne .L14
                                   .L18:
                                     pop {r4, r5, r6, lr}
                                     bx  lr
    []s
    Fred
    Last edited by flp1969; 04-06-2019 at 10:11 AM.

  8. #8
    Registered User
    Join Date
    Mar 2019
    Posts
    51
    @flp1969
    Thank you Sir! I am newbie try to take concept from my seniors but love to do things by my own ways

  9. #9
    Registered User
    Join Date
    Feb 2019
    Posts
    647
    Quote Originally Posted by rm82co View Post
    @flp1969
    Thank you Sir! I am newbie try to take concept from my seniors but love to do things by my own ways
    As I said: Your routine is fine! As a "senior" I like to drop some advice here and there from time to time!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 08-06-2011, 11:58 AM
  2. Replies: 12
    Last Post: 03-27-2009, 02:36 PM
  3. showbits(int)
    By Bhushan in forum C Programming
    Replies: 15
    Last Post: 07-27-2007, 03:51 PM
  4. showbits
    By sanjeev_ddas in forum C Programming
    Replies: 6
    Last Post: 09-07-2006, 01:36 AM
  5. showbits()???
    By kashifk in forum C Programming
    Replies: 5
    Last Post: 06-01-2003, 05:24 AM

Tags for this Thread