I want to convert a four character string (i.e. four characters) into a long (i.e. convert them to ASCII codes and then put them into the long).
As I understand it, this is done by writing the first character to the first byte of the long, the second to the adjacent memory location, and so on. But I don’t know how to do this in C++.
Can someone please point me in the right direction?
Thanks in advance.
Here’s your set of four characters:
Now we assemble a 32-bit unsigned integer:
Here I assume that
buf[0]is the least significant one; if you want to go the other way round, just swap the indices around.Let’s confirm:
Important: Make sure your original byte buffer is unsigned, or otherwise add explicit casts like
(unsigned int)(unsigned char)(buf[i]); otherwise the shift operations are not well defined.Word of warning: I would strongly prefer this algebraic solution over the possibly tempting
const uint32_t n = *(uint32_t*)(buf), which is machine-endianness dependent and will make your compiler angry if you’re using strict aliasing assumptions!As was helpfully pointed out below, you can try and be even more portable by not making assumptions on the bit size of a byte:
Feel free to write your own generalizations as needed! (Good luck figuring out the appropriate
printfformat string 😉 .)