Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conversion from int to 4 byte char 1

Status
Not open for further replies.

DavidRogers

Programmer
Aug 16, 2001
1
GB
Hi there,

I am just going home with this problem. I just need to two functions to split off an int into 4 bytes and back again.

I will mull this one over in the pub tonight. I seem to remember doing a 2 byte with % 256 and / 256...

Hope somebody can help!

Cheers,

Dave.
 
If i understand this correctly, you could do something like this.

union bytes
{
int value;
char four_bytes[4];
};

bytes b;
b.value = some_value;
(int)four_bytes[0]; // bits 7-0 OR 31-24 depending on ENDIAN
etc..


OR you could write a generic function like:

int getBits(int value, int lowBit, int highBit)
{
if(lowBit>highBit)
{
int temp = lowBit;
lowBit=highBit;
highBit=temp;
}

unsigned long maskValue = 0;

for(int i = lowBit;i<=highBit;i++)
{
maskValue |= 1<<i;
}

return (value32 & maskValue)>>lowBit;
}


Matt


Matt
 
To convert from int to char:
int i;
char ichar[4];

sprintf(ichar,&quot;%4d&quot;,i);

The other direction use the function atoi;


hnd
hasso55@yahoo.com

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top