Bit operation and look-up table

Is there any utility or library provides a simple function to convert a hex to binary and then depending on bit set assigning decimal value ?
This will convert hex to binary but i want to manipulate each bit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int getBit(int n, int k)
{
    return (n & (1<<k)) != 0;
}

int main()
{
    int n = 0x05;
    for (int k = 3; k>=0; k--)
    cout << getBit(n,k);
    cout << endl;
    return 0;
} 


This will convert 0x05 = 0101 . After this how to check each bit and if it is set means depending on position assign decimal value.
Say from left to right first bit: 0=0x01;
2nd bit: 1=0x02;
3rd bit: 0=0x03;
4th bit: 1=0x04;
Here am i doing in right way ????
Its giving me result like bit wise set into equivalent hexadecimal bit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
int count=0;
using namespace std;

int getBit(int n, int k)
{	
	unsigned z,x=0;
  	x=(n & (1<<k)) != 0;
	cout<<x;
	cout<<endl;
	if(x==0)
	{
	count+=1;
	}
	else
	{
	count+=1;
	std::cout << "Hex value :0x"<<std::hex << count << '\n';
        }	
}

int main()
{	
	unsigned y=0;
	long int n = 0xBFBFB993;
	for (int k = 63; k>=0; k--)
	{
	getBit(n,k);
	}	
	return 0;
} 
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>
#include <bitset>
// int count=0; // avoid
// using namespace std; // also avoid

// int getBit(int n, int k)
bool getBit( unsigned int n, std::size_t pos ) // favour unsigned integers for bit operations
{  return n & ( 1U << pos ) ; }

int main()
{
    constexpr std::size_t NBITS = std::numeric_limits<unsigned int>::digits ;

    const unsigned int n = { 0xBFBFB993 } ; // {} make sure there is no narrowing conversion
    for( std::size_t pos = NBITS-1 ; pos < NBITS ; --pos ) std::cout << getBit( n, pos ) ;
    std::cout << '\n' ;


    std::cout << std::bitset<NBITS>(n) << '\n' ; // test correctness
}

http://coliru.stacked-crooked.com/a/17d929cd0558b57d
Topic archived. No new replies allowed.