Nov 8, 2009

Convert a byte array to an int and vice versa

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > Programming > Programming General > C, C++ & Visual C++

Convert a byte array to an int and vice versa

helix
Due to a horrible file i/o system I have to use at work (reads in a file and returns an array of bytes), I needed to write a conversion scheme for making these bytes into ints and back again. I'll post it up here for you guys. Note: this only handles the PC's little endian-ness.

uint32 GetInt32( uint8 *pBytes )
{
return (uint32)(*(pBytes + 3) << 24 | *(pBytes + 2) << 16 | *(pBytes + 1) << 8 | *pBytes);
}

void Int32ToUInt8Arr( int32 val, uint8 *pBytes )
{
pBytes[0] = (uint8)val;
pBytes[1] = (uint8)(val >> 8);
pBytes[2] = (uint8)(val >> 16);
pBytes[3] = (uint8)(val >> 24);
}

Comment/Reply (w/o sign-up)

tux_linux
HI!!!

You can convert these numbers by simple conversation!!

For example

BYTE b=3;
int i=(int) b; biggrin.gif biggrin.gif

you can do this with all your values;

i hope this is what you meen!

greetz tux

Comment/Reply (w/o sign-up)

qwijibow
i think you are confused tux.
the type of conversion you are talking about is type casting...

for example... type casting the character 'A' to an integer would create Integer 65 (the ascii code of A)

you can convert a char string into a long integer with the command strtol...
since your name is tux, ill asume your owrking in linux.. read the man page. "man strtol"

an example program...

CODE
long int number;
char string = new chat[ 1024 ];
cout << "neter a number" << endl;
cin >> string
number = strtol(string,(char **)NULL, 10);
cout << "you entered " << number << endl;
delete [ ] string


where the parameter 10 means use base 10 uniits, and the parameter NULL means use NULL as the string terminator.

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)


See Also,

*SIMILAR VIDEOS*
Searching Video's for convert, byte, array, int, vice, versa
advertisement



Convert a byte array to an int and vice versa

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com