Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google script convert to hex

Using Google Sheets, I want to store the value in a cell as a hexadecimal number.

But using Utilities.formatString("0x%2x", byte) stores the literal "0x%2x" in the cell.

Using Utilities.formatString("0x%2i", byte) stores "0x [number]" as expected.

Any idea what I am doing wrong?

Best regards Stefan

like image 892
StefanOfDenmark Avatar asked Jan 21 '26 08:01

StefanOfDenmark


1 Answers

Here is a function that may do what you want:

// function to convert decimal to hexadecimal 
function DecToHex(value) {    
  var result = "";
  while( value != 0 ) {
    var temp = value % 16;
    Logger.log(temp);
    var hex = temp < 10 ? String.fromCharCode(temp+48) : String.fromCharCode(temp+55);
    result = hex.concat(result);
    value = Math.floor(value/16);
  }
  if( ( result.length %2 ) != 0 ) result = "0"+result;
  result = "0x"+result;
  return result;
} 
like image 111
TheWizEd Avatar answered Jan 24 '26 11:01

TheWizEd