Friday, June 19, 2009

Back to Basics

Problem: How to detect stack growth direction and platform endianess?
Solution:read

#include <iostream>
using namespace std;

void stackdir(int i);
void printEndian(void);

/**
******************************************************************************
*
* Prints stack growth direction and platform endianess
*
******************************************************************************
*/
int main(int argc, char *argv[])
{
stackdir(10);
printEndian();
return(0);
}

/**
******************************************************************************
*
* Prints stack growth direction
*
******************************************************************************
*/
void stackdir(int i)
{
int j;

cout << "-----------------------" << endl;
cout << "[stack direction . . .]" << endl;
printf("param=%p, local=%p\n", &i, &j);

if (&j < &i) {
printf("grows down\n");
}
else {
printf("grows up\n");
}

j=0;
}

/**
******************************************************************************
*
* Prints platform endianess
*
******************************************************************************
*/
void printEndian()
{
cout << "-----------------------" << endl;
cout << "[endianess . . .]" << endl;

int i = 1;
char *p = reinterpret_cast<char *>(&i);

if (p[0] == 1) {
// Lowest address contains the least significant byte
cout << "little endian" << endl;
}
else {
cout << "big endian" << endl;
}
}
hide solution

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.