Jump to content
xisto Community
Sign in to follow this  
helix1405241470

Convert a byte array to an int and vice versa

Recommended Posts

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);}

Share this post


Link to post
Share on other sites

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...

long int number;char string = new chat[ 1024 ];cout << "neter a number" << endl;cin >> stringnumber = 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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.