This is a bad idea, for readability and for portability. Use array[0] * 10 + array[1]
if that's what you mean, and trust the the peephole optimizer to speed it up. If you must access the value via a pointer, use a char
pointer and write p[0] * 10 + p[1]
, which is easy to understand, perfectly legal, and portable.
Reasons why your code might not work are many, and this strongly suggests that what you're trying to do is dumb, or at least that you are in over your head.
The first one is that bytes range from 0–255, not from 0–9, and so if you do use this technique, and it works, you are going to get 1*256+2 =258, not 1*10+2 = 12. You are never, ever going to get 12. The computer does not work that way. This is why you have to call a function like atoi()
to convert a string like "12"
to the number 12 before you can do arithmetic on it.
If you have four byte ints, that would also be why you were getting some big number out: You think you're getting 1*256+2, but you're actually getting ((1*256+2)*256+3)*256+???. Also, as chris says in the comments, in such case your array is too small anyway, whence the ??? in the previous formula.
You could try using a short
instead of an int
and see if that works better; a short
is likely to be a 2-byte integer. But this isn't guaranteed, so it still won't be portable to systems with short
s longer than two bytes. Better practice is to find out the actual type on your system that corresponds to a two-byte integer (perhaps short
, perhaps something else), and then typedef something like INT2
to be that type, and use INT2
in place of int
.
Another potential problem is that your system might use a little-endian byte order, in which case the bytes in your array are in the wrong order to represent the two-byte machine integer you want, and your trick is never going to work. Even if can be made to work on your machine, it will break if you ever have to run the code on a little-endian machine. (Your comments elsewhere in this thread suggest that this is exactly what is going on.)
So just do it the easy way.