Weird string when i try to print hex as a string

hi so i've been trying to convert an int to a hexadecimal string some conversions work but when i try to print it in the monitor i get:
FFáâ7ó^}eøõ6‡·èÀ»[ðÿÿ‰âïå“}÷Žî֓ëõòQ÷źþkþÓù¦t|¼ýûßÏÿNOŒ;×ð]§€\ø™8WçÿM±¸½—š†¸ã/ó
here is my code



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

void loop(){
  String string_Of_Hex_Numbers;
  Decimal_To_Hex(255, string_Of_Hex_Numbers);
  Serial.println(string_Of_Hex_Numbers);
  
}

void Decimal_To_Hex(int decimal_Number_To_Be_Converted_To_Hex, String &hex_Number_Array_As_String){
   int place_Of_Hex_Symbol = 0;
   char hex_Number_Array[100];
   long quotient = decimal_Number_To_Be_Converted_To_Hex;
   long remaining_Number_After_Devision;
   while (quotient != 0)
   {
     //first we do a modulo on the quotient to see what remains
     //then we assign a symbol to it
       remaining_Number_After_Devision = quotient % 16;
       if (remaining_Number_After_Devision < 10){
           hex_Number_Array[place_Of_Hex_Symbol++] = 48 + remaining_Number_After_Devision;
           quotient = 0;
       }
       else{
           hex_Number_Array[place_Of_Hex_Symbol++] = 55 + remaining_Number_After_Devision;
           quotient = quotient / 16;
       }
   }
   hex_Number_Array_As_String = String(hex_Number_Array);
   
}

does anyone know where my error could be?

thanks in advance

From a brief look, i'd say your code is working. You get FF which is correct for 255. You just forgot to terminate the array of characters in hex_Number_Array.

Try changing this:

hex_Number_Array_As_String = String(hex_Number_Array);

to

hex_Number_Array[place_Of_Hex_Symbol] = 0;
hex_Number_Array_As_String = String(hex_Number_Array);

of course you could also do

void setup() {
  Serial.begin(9600);
  Serial.println(255, HEX); 
}

void loop(){}

yes this is awesome. I am printing the string in reverse but i can find a way to flip it so thats easy enough.

this would work but I need the value as a string not as an int :frowning:

Why do you need it as a string?

void setup() {
  char hex_string[6];
  Serial.begin(9600);
  snprintf(hex_string,sizeof(hex_string);"%X",255);
  Serial.println(hex_string); 
}

void loop(){}

Or, for much smaller but less flexible code, use itoa():

itoa(255, hex_string, 16);

I was wondering which direction this was going… :clown_face: