开发者

Convert integer/decimal to hex on an Arduino?

How can an integer or decimal variable be converted into a hex string? I 开发者_如何学JAVAcan do the opposite (convert hex to int) but I can't figure out the other way.

This is for Serial.print() hex values in an array.


Take a look at the Arduino String tutorial here. The code below was taken from that example.

// using an int and a base (hexadecimal):
stringOne =  String(45, HEX);   
// prints "2d", which is the hexadecimal version of decimal 45:
Serial.println(stringOne);  

There are plenty of other examples on that page, though I think for floating point numbers you'll have to roll your own.


There's a simple solution, just use:

Serial.print(yourVariable, HEX);


The Streaming library provides a built in way to do this:

#include <Streaming.h>
...
Serial << "45 in hex is " << _HEX(45) << endl;

You will need to download the Library from http://arduiniana.org/libraries/streaming/ and place it in a subdirectory of your Sketchbook folder. The Menu File-Preferences will show you where that is.

This library can also be used when outputting to LCDs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜