java - 如何在 C 中执行此操作(来自 Java)

标签 java c

我目前正在学习很棒的 Arduino 和一些 C,我正在努力让它发挥作用。我如何在 C 中执行以下操作!

String val = "";
while(true) {
    thisChar = "2"; // this will be a "char" in C, this is finished in C, it's reading from a stream, the "2" is just an example
    if(val.length < 3) {
        val = val + thisChar;
    } else {
        int num = val;
        // i will do something with my new int thing
        val = "";
    }
}

所以我试图从根本上获取一个 char,将其中三个组合成一个字符串,将其转换为一个 int,然后用它做一些事情。以三为单位发送的数字是 000 到 100 之间的任何数字!

我会发布我的想法。

char val[];
if (client.available() > 0) { //finns åtmminstone 1 klient?
  char thisChar = client.read(); //läser av nästa byte från servern
  if( thisChar == 'H' ){
    Serial.println("HIGH from client");
    digitalWrite(led, HIGH); // lys LED
  }
  else if( thisChar == 'L' ){
    Serial.println("LOW from client");
    digitalWrite(led, LOW); // släck LED
  }
  else {
    Serial.println(thisChar);
    int len = strlen(val);
    if(len < 3) { // saknas fortfarande tecken tex 0 eller 02
      val = val + 
    }
    else { // värdet är komplett tex 010 eller 100
      val = "";
    }
  }
}

回答: 感谢@morgano 的聊天,他能够从所有三个答案中拼凑出以下代码!

  static char val[4] = {0}; //we only care about 3 digit numbers. 
  static int len = 0; 
  //... code blabla
  char thisChar = client.read(); //läser av nästa byte från servern
  //... code blabla
  else { 
    val[len] = thisChar; 
    len++;  
    if(len > 2) { // värdet är komplett tex 010 eller 100 
      int i;
      sscanf(val, "%d", &i);
      Serial.println(i);
      //Serial.println(val);
      len = 0; 
      //val[3] = 0; 
    }
  }

最佳答案

您所拥有的看起来不错——您只需要决定如何将文本“附加”到您的 char 数组。

我会保留一个描述字符串当前“长度”的变量。所以,你可以尝试这样的事情:

char val[4]; //we only care about 3 digit numbers. 
int valLength = 0; //No characters in the string yet.

char thisChar = client.read();

val[3] = '\0';  /* Need to terminate the string, or else... */
if (valLength < 3) {
  val[valLength] = thisChar;
  valLength++;
}
else {
  int myIntVal = strtol(val, 0, 10); //I believe this is the right syntax.  I'm not 100% sure.
  val[0] = 0;
  val[1] = 0;
  val[2] = 0;
}

关于java - 如何在 C 中执行此操作(来自 Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22366477/

相关文章:

java - 如何在日期选择器 appium 中发送日期(Android API 19,版本 1.2.4.1)

c - 当你有一个指向结构指针的指针时,你如何使用 realloc?

c - 处理有符号 int 数组,就好像它包含无符号值一样

c++ - 在 C 和 C++ 中返回 void 类型

java - Spring Bean ClassNotFound 如何调试?

java - 为什么要在公共(public) API 中包含未实现的方法,例如 Thread.destroy()?

java - 如何下载网页上的评论(Android)

java - 如何将一个android包分成多个包

c++ - 测试返回三角形类型的函数

在 OpenGL 中更改投影