How to use map with hex values??
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 x=0;
x=(n & (1<<k)) != 0;
cout<<x;
cout<<endl;
if(x==0)
{
count+=1;
}
else
{
count+=1;
cout<<"count="<<count<<endl;
std::cout << "Hex value :0x"<<std::hex << count << '\n';
return count;
}
}
int main()
{
long int n = 0xBFBFB993;
for (int k = 63; k>=0; k--)
{
getBit(n,k);
return 0;
}
|
This code will give hex value how to store them in map???
Last edited on
Hi, I was playing around (just for fun) with your question and come up this custom Hex class:
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <map>
using std::map;
#include <string>
using std::string;
#include <iomanip>
using std::hex;
using std::setw;
#include <utility>
using std::make_pair;
#include <sstream>
using std::stringstream;
#include <iostream>
using std::cin;
using std::endl;
using std::cout;
#include <memory>
using std::shared_ptr;
using std::make_shared;
template<typename T>
class Hex final
{
public:
// constructor will save the value and "display format" (as string)
explicit Hex(T hex_value) : m_hex(hex_value)
{
stringstream stream;
stream << "0x" << setw(sizeof(T)) << hex << hex_value << endl;
m_string = stream.str();
}
// to simply show the string value call: hex_object()
const string& operator()() const
{
return m_string;
}
// get value
const T& get_value() const
{
return m_hex;
}
private:
T m_hex;
string m_string;
// deleted
Hex(Hex&&) = delete;
Hex(const Hex&) = delete;
Hex& operator=(Hex&&) = delete;
Hex& operator=(const Hex&) = delete;
};
int main()
{
// types defining our custom hex class and value
typedef const unsigned long ulong;
typedef Hex<ulong> type_hex_object;
typedef shared_ptr<type_hex_object> type_hex; // let the map copy pointers only
// hex value for testing
ulong hex_value = 0xBFBFB993;
// map<key, value>
map<ulong, type_hex> test_map;
// create custom hex object
type_hex hex = make_shared<type_hex_object>(hex_value);
// insert new hex value
test_map.insert(make_pair(hex->get_value(), hex));
// access our hex value
auto find = test_map.find(hex_value);
if (find != test_map.end())
{
// get hex object
auto result = find->second;
// re-use stored hex value
ulong ret_value = result->get_value();
// show retrieved value
cout << ret_value << endl;
// show stored value
cout << (*result)();
}
else
{
cout << "value not found" << endl;
}
cout << "done..";
cin.get();
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.