Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using mosquitto_pub
. The buffer is apparently not zero-terminated.
If these characters represent an integer value, then the way to retrieve it as an integer value would be
char buffer[128];
// Make sure here that `length` is smaller than the above buffer size.
// Otherwise, you'd need a bigger buffer
// Form a C-string from the payload
memcpy(buffer, payload, length);
buffer[length] = '\0';
// Convert it to integer
char *end = nullptr;
long value = strtol(buffer, &end, 10);
// Check for conversion errors
if (end == buffer || errno == ERANGE)
; // Conversion error occurred
else
Sterial.println(value);
Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be
// Build a `scanf` format string that will read no more than `length`
// characters without relying on zero-termination of the payload
char format[16];
snprintf(format, sizeof format, "%%%ud", length);
// Convert the payload
int payload_value = 0;
if (sscanf((const char *) payload, format, &payload_value) == 1)
Serial.println(payload_value);
else
; // Conversion error occurred
However, this approach is less protected from integer overflow than the previous one.
Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple
// Convert C-string to integer
char *end = nullptr;
long value = strtol((const char *) payload, &end, 10);
// Check for conversion errors
if (end == buffer || errno == ERANGE)
; // Conversion error occurred
else
Sterial.println(value);
No extra buffers required.
byte *
toint
, then you already have it, assuming thatint
is large enough to store an address on your platform. But what would be the point of this? Yourpayload_value
is an address.