### Bytes to integer

Hello all.
I use to program in VB,but decided recently to try also C++.
My question is,how can I convert bytes values into integer.
I read a file using char[] and I want to convert specific bytes to integer.
For example,to convert the bytes from char[57] to char[60] into integer.

In VB there is a function bitconverter.ToInt32(array() as byte,start_pos as integer).

Thanks for helping.
Typically C people just write it themselves.

Here's one:
 ``123456789101112`` ``````template IntegerType bitsToInt( IntegerType& result, const unsigned char* bits, bool little_endian = true ) { result = 0; if (little_endian) for (int n = sizeof( result ); n >= 0; n--) result = (result << 8) +bits[ n ]; else for (unsigned n = 0; n < sizeof( result ); n++) result = (result << 8) +bits[ n ]; return result; }``````

Hope this helps.
Can you please give a small example on how to call this function?

Thank you.
Last edited on
I think that you want to do readInt32() like in VB, right?

Some bytes in a file are just one value (one byte long):

 `` `` ``int Int32 = (int)myByte;``

Simple brace conversion...

But since Int32's are 4 bytes long....

 ``1234567`` ``````byte MyBytes[4]; //set values to this also. int Int32 = 0; Int32 = (Int32 << 8) + MyBytes[3]; Int32 = (Int32 << 8) + MyBytes[2]; Int32 = (Int32 << 8) + MyBytes[1]; Int32 = (Int32 << 8) + MyBytes[0];``````

Now your Int32 is set to the combination of those 4 bytes!

Bytes can appear as something like (34, 45, 13, 30), but are a very large number in Int32 form. For this example it's actually equal to...

504180002 (try it!)

Also, a 'byte' value in C++ is an unsigned char:

 `` `` ``typedef unsigned char byte;``
Last edited on
Thanks Mayflower,that is exactly what I have been looking for.
@mayflower: That doesn't cover both endian types. I would suggest using Duoas's solution.
Last edited on
Topic archived. No new replies allowed.