Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 
    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.



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