Here is my code:
#include <iostream>
#include <stdint.h>
using namespace std;
//converts high endian to little endian
uint32_t format(const char* &bytes)
{
return (uint32_t)((bytes[0] << 24) |
(bytes[1] << 16) |
(bytes[2] << 8) |
(bytes[3]));
}
uint32_t normal(const char* &bytes)
{
return (uint32_t)((bytes[3] << 24) |
(bytes[2] << 16) |
(bytes[1] << 8) |
(bytes[0]));
}
int main()
{
char bytes[4];
bytes[0]= 0x01;
bytes[1]= 0x23;
bytes[2]= 0x45;
bytes[3]= 0x67;
printf("0x%08x\n", normal(bytes);
printf("0x%08x\n", format(bytes);
}
I have a char array of size 4 called bytes. Each element in bytes stores a byte, which, collectively, I treat as a 32 bit unsigned int. My goal is to pass bytes into format() and this will return the little endian form of the number in bytes (which is currently stored in high endian). My issue is, I want to pass the array as a reference so that it doesn't create extra memory for the function parameters. Not only that, I also want to make it so that the function can't change the elements in bytes. For this, I tried: uint32_t format(const char* &bytes); and passed bytes like this: format(bytes) but this is giving me an error.
When I wrote it like this instead: uint32_t format(char* const &bytes), the error stopped but this is not what I wanted since this is a reference to a constant pointer to a character meaning I can't change the pointer itself but I can change the value it points to. What I want is the opposite: I want a reference to a pointer to a constant character so that I may be able to change the pointer but I can't change the value it is pointing to.
Finally, I want to add that I could have done this easily without a reference, but, as I mentioned earlier, this will cause memory to be allocated for the function parameters each time it is called which is not what I want.