2

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.

4

2 回答 2

5

类型的指针uint8_t不能指向类型的对象int16_t;您需要复制 的值firstVal,但因此您需要一个单独的对象来获取该值。

uint8_t firstValAbs = firstVal >= 0 ? firstVal : -firstVal;
uint8_t* secondVal = &firstValAbs;

注意:uint8_t x = -34不会给你 的绝对值,即它不会-34导致34. 您宁愿得到 的二进制补码-34,即255-34+1 == 222

于 2018-12-11T22:02:49.033 回答
3

int16_t使用 16 位(-32,768 到 32,767)存储带符号的数值。

uint8_t使用 8 位(0 到 255)存储无符号数值。

如果您确定您的int16_t值在更改符号后适合uint8_t,您可以分配它:

int16_t firstVal = -76;
uint8_t secondVal = -firstVal;

现在,如果您需要指向第二个值的指针,您可以创建它。您不能直接指向,firstVal因为您需要存储更改的值。

uint8_t* secondValPointer = &secondVal;

uint8_t*可以解释为指向库中字符的指针。通常,您应该为此目的使用 char (也是 8 位,但如果它是有符号或无符号的,它是实现定义的)。您可以将此指针转换为 c har*,尽管您需要告诉编译器您要使用 reinterpret_cast 在指针之间进行转换:

char *secondValAsChar = reinterpret_cast<char*>(secondValPointer);

现在,您可以将此指针视为指向字符的指针。例如,以下代码将打印“L”,因为 L 的 ASCII 代码是 76:

std::cout << *secondValAsChar << std::endl;

但是,您必须非常小心这个指针,因为 secondValAsChar 不是以空结尾的字符串,因此您不能使用旧的常用方法,如strcat.

于 2018-12-11T23:12:29.743 回答