我有十六进制值,例如 0300E0678C,我将其转换为长整 12899608460 但在这个阶段,我必须只打印长整 int - 9608460 中的最后 7 个数字,所以我尝试使用 %lld 冲刺,但它什么也没返回。 有什么想法怎么做吗?
#include <SoftwareSerial.h>
#include <ID20Reader.h>
#include <PriUint64.h>
int rx_pin = 3;
int tx_pin = 2;
char output[16];
long long int numer;
char buf[50];
ID20Reader rfid(rx_pin, tx_pin);
void setup() {
Serial.begin(9600);
tone(4, 3400, 1000);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
rfid.read();
if(rfid.available())
{
digitalWrite(LED_BUILTIN, HIGH);
String code = rfid.get();
Serial.println(code);
tone(4, 4000, 500);
char bufor[12];
code.toCharArray(bufor,12);
Serial.println(bufor);
numer = hexToDec(bufor);
Serial.println(PriUint64<DEC>(numer));
delay(500);
digitalWrite(LED_BUILTIN, LOW);
}
}
long long hexToDec(String hexString) {
long long decValue = 0;
int nextInt;
for (int i = 0; i < hexString.length(); i++) {
nextInt = int(hexString.charAt(i));
if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
nextInt = constrain(nextInt, 0, 15);
decValue = (decValue * 16) + nextInt;
}
return decValue;
}
我愿意:
...
byte myData[16];
int i = 0;
...
numer = hexToDec(bufor);
i=0;
do
{
byte y = numer % 10;
myData[i] = y;
numer = numer / 10;
i++;
}
while (numer != 0);
for (int i = 6; i >= 0; i--)
{
Serial.print(myData[i]);
}
第一次测试是乐观的;)
尝试这样的事情应该可以解决问题:
#include <iostream>
#include <string>
int main()
{
// Example given
constexpr long long int p = 0x300E0678C;
std::printf("Example: %lldn", p);
// Create new string with p
std::string tempStr(std::to_string(p), 0);
long long int pLast7 = std::atoll( // Convert string to long long integer
tempStr.substr(tempStr.length() - 7, 7) // cut the string 7 characters from the end, and have the next 7 characters returned
.c_str()); // convert it to C-style string (const char*) for use with atoll
std::printf("Last 7: %lldn", pLast7);
}
这是 cpp.sh 链接,如果您想亲自尝试一下!
cpp.sh/53evd