简体   繁体   中英

Convert a HEX string to long in C++

I'm writing my first BLE system for Ardunio and I'm building it on top of an already working system for controlling RGB strip, and currently, I'm using the HEX numbers to know what I'm setting where.

OK reworking the question,

#define BLE_RX 5
#define BLE_TX 4

SoftwareSerial BLE(BLE_RX, BLE_TX);

// set the startup color to white
unsigned long color = 0xFFFFFF;
// hold the last color set so we can off / on without losing prior settings
unsigned long lastColor = 0x000000;

void setup() 
{
  Serial.begin(9600);
  BLE.begin(9600);

  pinMode(GREEN_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  Serial.println("hello world");
}


void loop() {
  long r = ((color >> 16) & 0xFF);
  long g = ((color >> 8) & 0xFF);
  long b = (color & 0xFF);
  char data[100];
  analogWrite(RED_LED, r);
  analogWrite(GREEN_LED, g);
  analogWrite(BLUE_LED, b);

  readBLE();
}

long hstol(String recv){
  char c[6];
  recv.toCharArray(c, 6);
  return strtol(c, NULL, 16);
}

void readBLE(){
  if(BLE.available() > 0){
    String data = BLE.readString();
    if(data.length() == 6){
      lastColor = color;
      Serial.println(data);
      Serial.println(hstol(data));
      color = hstol(data);
    }
  }
}

When I first run my CPP the LED Strip is white as it should be if via BLE I send FF0000 (red), my LED's go green, this is my output

arduino 的串行输出

When FF0000 should Equal 16711680, 00FF00 = 65280 and 0000FF = 255

Source of error in your posted code: you are using an array of 6 characters while it should be 7 to hold the whole recv string. Your code is currently showing an undefined behavior because strtol searches for null/whitespace character to finish parsing which is never present within bounds in char c[6] .

I would recommend using this type of approach. It is just a single line thing, without requiring extra memory for some temporary character array. (Also saves the time, otherwise wasted in copying the hex string).

void setup() {
  Serial.begin(9600);
  
  String x1 = "FF0000";
  long y1 = strtol(x1.c_str(), NULL, 16); // <--
  Serial.print(y1); // prints 16711680
  Serial.println();
  
  String x2 = "0xFF0000";
  long y2 = strtol(x2.c_str(), NULL, 0); // <--
  Serial.print(y2); // prints 16711680
  Serial.println();
  
  long y3 = strtol(x2.c_str() + 2, NULL, 16); // <--
  Serial.print(y3); // prints 16711680
  Serial.println();
}

void loop() {
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM