I'm getting a bit tripped up on const char pointers lately.
I'm getting a message from a server that comes through as either a c style string, a standard library string, or a WString:
I'm sending down a buffer of 32bit values from my server that aren't ascii or utf text, they're just bit values I want to parse and read on the esp32 side:
I thought "oh, I'll just mask the bit values 32 bits at a time and right shift the data to get the message (in reverse order, but still I can work with that). The problem that I'm running into is that I can shift numbers but not strings or byte arrays.
I wrote out a function to allow me to grab a piece of the string 32 bits at a time and convert that into a number while using an offset:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{
uint32_t payload = 0;
for (uint8_t i = 0; i < 8; i++)
{
payload <<= 0;
payload += data[i + offset];
}
return payload;
}
But when I try to grab the first couple of 32 bit chunks the data isn't what I expected:
void handleGameFrame(const char *data, uint32_t length)
{
uint8_t phaseAndColission = get32BitInt(data, 32);
uint8_t player = getByte(data, 32 * 2);
Serial.print("data: ");
Serial.println(data);
Serial.print("phaseAndColission: ");
Serial.println(phaseAndColission, DEC);
Serial.print("player: ");
Serial.println(player, DEC);
}
yields:
I know the Serial.println(data);
isn't going to output anything b/c it's a c-string of non-printable values, but the other chunk grabbing isn't giving me the same output from my server. It's hard to verify everything without being able to see all of the bits in the overall data
pointer and I think I tied myself in (another) knot.
Is there a good way to parse 32 bit values out of a const c-string?
uint32_t
that are being pointed at with aconst char *
?const char *
) holds bits in it that can't beSerial.println
-ed because because even in 8 bit form they're not ascii/utf valid characters so nothing goes to the monitor.const uint32_t *ui32p = reinterpret_cast<const uint32_t *>(mycharptr);
If it's not aligned, you would do something likememcpy
it into an array or individual elements into a singleuint32_t
variable. There's nothing really "Arduino" here.