How do I convert an INT to HEX

Hello everyone, I am making a sort of jukebox and I need to convert an INT to HEX. I have a function called playSong that takes a number as string and sends a command to the MP3 player.

void playSong(String Snumber){
  int number = Snumber.toInt();
 // function to convert int to hex goes here
  sendCommand(CMD_PLAY_W_INDEX, 0, HEX);

the sendCommand takes a command, in this case CMD_PLAY_W_INDEX (play with index), and two bytes as parameters. For example if I want to play song number 123. It needs to translate 123 (base 10) in order to send it to the MP3 player. In this case it would be 0x7B (base 16).
I hope I explained it well.

Is there a function just like toInt(), but instead of to int, to hex?

The variable "number" is stored in binary. 0b01111011
Or hex. 0x7b
Or decimal. 123
Or octal. 0173

So you're saying it has to work just fine?

int 123 is 0x007B does not need any process.

But what is the value of your received string? In string format.

RV mineirin

is this a library function or something you are writing?

In this case, the value is 123.

I've just tried it out again but it still doens't work. Here is the snipped of the code from the sendCommand function:

void playSong(String Snumber){
  int number = Snumber.toInt();
  sendCommand(CMD_PLAY_W_INDEX, 0, number);

void sendCommand(byte command, byte dat1, byte dat2){
  Send_buf[0] = 0x7E;    //-> Every command should start with $(0x7E)
  Send_buf[1] = 0xFF;    //-> Version information
  Send_buf[2] = 0x06;    //-> The number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //-> Such as PLAY and PAUSE and so on
  Send_buf[4] = 0x01;    //-> 0x00 = not feedback, 0x01 = feedback
  Send_buf[5] = dat1;    //-> data1
  Send_buf[6] = dat2;    //-> data2
  Send_buf[7] = 0xEF;    //-> Ending byte of the command
  // The rest of this function
  // ...

When I run playSong("123") and look at the serial, it shows 123, meaning that dat2, does not get translated to byte/hex.

Note that playSong("1") does work, but playSong("123") does not.

Then sendCommand(CMD_PLAY_W_INDEX, 0, number );

should work.

RV mineirin

Unfortunately it does not work with string 123


You're welcome

I put the Serial.println(dat2) line there for the sake of debugging, in the code I left out it sends the Send_buf array to the MP3 player. Unfortunately playSong("1") works but playSong("123") does nothing.

I was pointing out the fallacy in your argument.

Thank you.

Hex, decimal, octal, ASCII ... these are all just different ways of representing the same data. That is only relevant for us humans. The computer doesn't care, the data is always stored and transmitted in binary. Text strings are also only binary data for the computer. Only when they are to be displayed somewhere does it make a difference how they are interpreted.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.