Conversion int to hex to byte


As I said in other post, I am building a packet to send by digimesh mode on xbee S1.

I am having some problems with conversion types.

I have a function which converts from int to string called String dec2hex(int value). With this function I introduce my sensor value and get an hex value (string):

String dec2hex(int sensor){
  char hexadecimal[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  String respuestaHex="";
  int valor = sensor;

    valor = valor / 16;
  while(valor%16 != 0);
  return flipString(respuestaHex); //I have to invert values because I get the hex number wrong. If I have to get 74D I get D47, so I invert it. I also did flipString function

After that, I want to introduce all sensor values in hex to a byte array:

byte packet[21];

to send it by Serial:

for(int x = 0; x < packetSize; x++){ //packetSize is defined upside. It is 21

But when I try to do this:

packet[17] = dec2hex(sensor1);

I got this error: hexadecimalOperaciones:134: error: cannot convert ‘String’ to ‘byte’ in assignment

I want to know if an easier way to convert number to hex exists to get it works. Also I need another fuction to convert from hex to decimal. For the moment I am using another function which gets a string and gives an int but I have the problem that it will receive a byte not a string.

I want to know if an easier way to convert number to hex exists to get it works.

Numbers are stored by the Arduino in binary. Binary, octal, decimal, and hexadecimal outputs are formats that the Arduino can produce for readability reasons. There is no reason for you to be trying to "convert" an integer value to hex format for sending. The format is for people to read, not computers.

packet[17] = sensor1;

Thanks PaulS.

for the moment I am trying it using Serial console without xbee.
Now I can see in Serial console all numbers of my packet.

Tomorrow I will try to send by xbee. But with the correct packet, I think the only problem could be the xbee's config.

but always it says that in Arduino IDE 1.0 I have to use just Serial.print() without format. Is there any way to get that?

What "it" is saving that you can't use DEC or HEX or BIN as the second argument? The only value that used to be a valid second argument that no longer is is BYTE.

Yes, I didn't know why it gave me that error. Now it works fine with HEX. that's why I edited my post. I thought nobody saw it :blush: