Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: All
Feb 22, 2000

Converting a Datatype to a Stream of Bytes

Sometimes you need to convert a certain datatype to its binary stream of bytes. An easy way to do it is to create a union that has two members: the datatype in question and an array of characters with a matching size. For example, to examine the binary representation of a pointer to a member function, the following program assigns the address of the member function f() to the union member p and then it examines the corresponding character array bin_ptr:

 
  class A 
  {
   public:
    void f();
  };

  typedef void (A::*pmf)(); // pointer to member 
  union U
  {
    pmf p;
    unsigned char bin_ptr[sizeof(pmf)];
  };
  int main()
  {
    U u = {0}; // initialize 
    u.p = &A::f; // assign member function's address
  
    for (int j = 0; j< sizeof (U); j++)
      cout<< (int)u.bin_ptr[j]<<" "; // display each byte in p
  }
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date