C reverse bits in unsigned integer

前端 未结 12 877
一整个雨季
一整个雨季 2020-11-30 10:18

I\'m converting an unsigned integer to binary using bitwise operators, and currently do integer & 1 to check if bit is 1 or 0 and output, then right shift by 1 to divide

12条回答
  •  再見小時候
    2020-11-30 10:53

    You could reverse the bits like you output them, and instead store them in another integer, and do it again :

    for (i = 0; i < (sizeof(unsigned int) * CHAR_BIT); i++)
    {
      new_int |= (original_int & 1);
      original_int = original_int >> 1;
      new_int = new_int << 1;
    }
    

    Or you could just do the opposite, shift your mask :

    unsigned int mask = 1 << ((sizeof(unsigned int) * CHAR_BIT) - 1);
    while (mask > 0)
    {
      bit = original_int & mask;
      mask = mask >> 1;
      printf("%d", (bit > 0));
    }
    

    If you want to remove leading 0's you can either wait for a 1 to get printed, or do a preliminary go-through :

    unsigned int mask = 1 << ((sizeof(unsigned int) * CHAR_BIT) - 1);
    while ((mask > 0) && ((original_int & mask) == 0))
      mask = mask >> 1;
    do
    {
      bit = original_int & mask;
      mask = mask >> 1;
      printf("%d", (bit > 0));
    } while (mask > 0);
    

    this way you will place the mask on the first 1 to be printed and forget about the leading 0's

    But remember : printing the binary value of an integer can be done just with printf

提交回复
热议问题