Endianness

I'm currently working on a project that uses a pointer to capture and then display and long int value entered by the user. When entering the value 2140118959 I receive Af 9f 8f 7f, I'm looking to get 7f 8f 9f Af. I know this is because of little endian format. Hints?

#include <iostream>
using namespace std;

void Show_hex(void *p, int); //Function Prototype

//*****************************
// main()
//*****************************

int main() {
//Declare and initialize sample arrays and variables
long int long_var;
cout << "\nHexadecimal dump: \n";

cout << "Please enter value to be displayed in hex: ";
cin >> long_var;

//Arrays and variables are passed to hex_dump() function
Show_hex(&long_var, sizeof(long_var));
return 0;
}

//*****************************
// show_hex() function
//*****************************

void Show_hex(void *void_ptr, int elements) {
unsigned char digit, high_nib, low_nib;

for(int x = 0; x < elements; x++) {
digit = *((char *)void_ptr + x);
high_nib = low_nib = digit; //copy in high and low nibble
high_nib = high_nib & 0xf0; // Mask out 4 low-order bits
high_nib = high_nib >> 4; // Shift high bits left
low_nib = low_nib & 0x0f; // Mask out 4 high order bits
//Display in ASCII hexadecimal digits
if(low_nib > 9)
low_nib = low_nib + 0x37;
else
low_nib = low_nib + 0x30;
//Same thing for high nibble
if(high_nib > 9)
high_nib = high_nib + 0x37;
else
high_nib = high_nib + 0x30;


cout << high_nib << low_nib << " ";
}
cout << "\n";
system("pause");
}

THANKS
Left shift destination, OR LS byte from source to destination, right shift source, repeat.

EDIT: Alternatively, you may use a byte array as the destination, which would make the code work consistently regardless of native endianness.
Last edited on
You can use the (non-standard-c, but widely available) function "htonl" to make sure your integers are in big-endian. The plus is, that it won't do anything to your integer if you are already running on a machine with big-endian storage.

On linux, its in netinet/in.h. On windows, include winsock2.h.

Ciao, Imi.
Topic archived. No new replies allowed.