I have a library driven result stored as an int16_t value (and it is a negative, which I can use the absolute value of) and another library function that requires this value a few steps later in the form uin8_t*. How can this be done without using String?
The following code works, but uses dreaded Strings. Is there a way to do this without invoking String or std::string?
void setup() {
Serial.begin(9600);
}
void loop() {
delay(5000);
String initialVal= String(-fetchInt());
Serial.print("Initial value is: ");Serial.println(initialVal);//prints "76"
uint8_t medianVal[sizeof(initialVal);
medianVal.getBytes(medianVal, sizeof(initialVal));
Serial.print("median value is: ");Serial.println(medianVal);//prints "76"
uint8_t* finalVal = medianVal;
Serial.print("final value is: ");Serial.println((char*)finalVal);//prints "76"
}
int16_t fetchInt(){
return -76;
}
So, how can I turn int16_t into uint8_t*?
It has been pointed out in comments below that
Serial.println(static_cast<unsigned>(*finalVal));
works, but this solution converts the uint8_t to an unsigned int and the method requires uint8_t*.
I come from Java and the like and it seems crazy that it is so hard to convert an integer to a string.
A pointer of type uint8_t
cannot point to an object of type int16_t
; you need to copy the value of firstVal
, but therefore you'll need a separate object to take on the value.
uint8_t firstValAbs = firstVal >= 0 ? firstVal : -firstVal;
uint8_t* secondVal = &firstValAbs;
Note: uint8_t x = -34
will not give you the absolute value of -34
, i.e. it will not result in 34
. You'll rather get a two's complement of -34
, i.e. 255-34+1 == 222
.