0

Ok so I have this

Commands.hex = {
  name: 'hex',
  help: "I'll convert your steamid for you",
  timeout: 10,
  level: 0,
  fn: function (msg, suffix) {
    msg.reply('Steam64').then((m) => {
      m.edit('<@' + msg.author.id + '>, Steam ID Converted: ' + suffix.toString(16)).slice(-2).toUpperCase()
    })
  }
}

i'm trying to get it to do what this website does http://www.binaryhexconverter.com/decimal-to-hex-converter

picture of what it's doing

I'm just trying to get it to convert for my discord bot, thank you!

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Jake Pavek
  • 15
  • 1
  • 1
  • 5
  • What type does 'suffix' come to you as? If it's a string then I imagine you have to call `parseInt` on it first since `toString(16)` will only work correctly if suffix is already an integer. – Khauri Nov 06 '17 at 19:56
  • suffix is the users message I believe. as you see it says !!hex 76561198205234861 @KhauriMcClain – Jake Pavek Nov 06 '17 at 19:59
  • Yes I understand. But most likely the user's message will be passed a string rather than an integer, and thus calling `toString(16)` on a string will not work. `(10).toString(16)` will return "a", but `("10").toString(16)` will return "10" – Khauri Nov 06 '17 at 20:03
  • Sorry I am learning tried this `m.edit('<@' + msg.author.id + '>, Steam ID Converted: ' + parseInt(suffix).toString(16))` @KhauriMcClain – Jake Pavek Nov 06 '17 at 20:17
  • that worked, thank you! – Jake Pavek Nov 06 '17 at 20:19
  • actually this is weird http://prntscr.com/h71s23 I get that on the website but on discord I get this http://prntscr.com/h71sgf – Jake Pavek Nov 06 '17 at 20:32

1 Answers1

1

As it turns out your value: 76561198262006743 is much greater than Number.MAX_SAFE_VALUE, which is (2^53 -1). This will lead to undefined behavior when trying to do arithmetic.

For example, on Google Chrome when typing just the number into the console and pressing enter, that value became 76561198262006740 (note the 3 at the end became a 0), which meant the hex conversion was incorrect as well.

An easy solution is, since you already have the value as a string, would be to perform your own decimal->hex conversion.

One such algorithm can he found here: https://stackoverflow.com/a/21668344/8237835

A small comparison of the results of Number#toString(16) and dec2hex(String):

function dec2hex(str){ // .toString(16) only works up to 2^53
    var dec = str.toString().split(''), sum = [], hex = [], i, s
    while(dec.length){
        s = 1 * dec.shift()
        for(i = 0; s || i < sum.length; i++){
            s += (sum[i] || 0) * 10
            sum[i] = s % 16
            s = (s - sum[i]) / 16
        }
    }
    while(sum.length){
        hex.push(sum.pop().toString(16))
    }
    return hex.join('')
}

num = "76561198262006743"

console.log("dec2Hex: " + dec2hex(num))

console.log("toString: " + parseInt(num).toString(16))
Khauri
  • 3,753
  • 1
  • 11
  • 19