http://www.java2s.com/Tutorial/Cpp/0040__Data-Types/Printinganunsignedintegerinbits.htm

 

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

int main()
{
   unsigned value = 123;
   const int SHIFT = 8 * sizeof( unsigned ) - 1;
   const unsigned MASK = 1 << SHIFT;

   cout << "MASK=" << MASK << endl ;
   cout << "SHIFT=" << SHIFT  << endl ;

   for ( int i = 1; i <= SHIFT + 1; i++ )
   {
      cout << ( value & MASK ? '1' : '0' );
      value <<= 1;

      if ( i % 8 == 0 )
         cout << ' ';
   }

   cout << endl;
   return 0;
}

 

g++ bits.cpp -o bits.exe

MASK=2147483648
SHIFT=31
00000000 00000000 00000000 01111011

==================================================

http://stackoverflow.com/questions/2249731/how-to-get-bit-by-bit-data-from-a-integer-value-in-c

 程式裡面的 mask,mask_n,thebit 都改成 unsigned int , print 出來的值才會對 !!!

#include <stdio.h>
#include <stdlib.h>

int *get_bits(int n, int bitswanted){
  int *bits = (int*) malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    unsigned int mask =  1 << k;
    unsigned int masked_n = n & mask;
    unsigned int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n= -123  ;

  int  bitswanted = 32 ;
  int mask =  1 << 31 ;
  printf("(%d)\n",mask) ;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()