Can anyone point out whats going wrong with my code.
I have tried to convert an integer (-998) to a character array in hex form and want to read it back as the same integer but it is displaying some other number.
int *h = (int *)ch;
what this line does is assign h the address of the first element of ch, so *h is the value of the first four bytes of ch viewed as an int. what you want to do could be done like this:
Umm. what I want to do is create a char array of the interger split into highbyte and lowbyte.
I want to send the integer over a serial com port which only receives 8 bytes at a time. and by the way the device im interfacing with has a 16 bit int.
#include <cstdlib>
#include <iostream>
#include <stdio.h>
usingnamespace std;
int main()
{
int number;
unsignedchar * split;
cout << "enter number: ";
cin >> number;
split=(unsignedchar*)&number;
cout << "byte 0: " << (int)*split << endl;
cout << "byte 1: " << (int)*(split+1) << endl;
cout << "byte 2: " << (int)*(split+2) << endl; //<-comment this out for 16-bit ints
cout << "byte 3: " << (int)*(split+3) << endl; //<-comment this out for 16-bit ints
system("pause");
return 0;
}
one more important thing you have to bear in mind is endianness. my machine stores the lobyte on the first position and the hibyte on the last. yours might do it the opposite way
Thank you master roshi. that solved my problem. now all i have to do is access the integer in microcontroller by saying (int *)k = (int *) split. and the integer is *k.