David Jeong
David Jeong

Reputation: 119

How to get true or false if a number is hexadecimal or not?

I want a method which if given a hexadecimal number (e.g. 0x01) returns true. I tried with a string argument, but I need number type check! For example:

isHex(0x0d) //-> true
isHex(12)   //-> false

Upvotes: 4

Views: 9787

Answers (6)

PassingThrough
PassingThrough

Reputation: 11

I don't know if this helps but I use logic like below to block dodgy domain scripts from loading in a browser, such as this URL:

https://0e29fa5ee4.09b074f4cf.com/165575ce5432f25ac96b16e917b1750c.js

The logic used once components have been extracted from the URL is basically...

var S='0e29fa5ee4';

var IsHex=parseInt(S,16).toString(16)===S.toLowerCase();

NB: Of course you may also lose some valid domains such as "abba" so a little more logic may be needed.

Upvotes: 1

Emanuel Friedrich
Emanuel Friedrich

Reputation: 344

^([0-9A-Fa-f])+$

is the unique pattern that is working for me

Upvotes: 1

Andrew Marshall
Andrew Marshall

Reputation: 96934

This is not possible as hexadecimal number literals are just another way of representing the same number (translated during parsing) and there’s no way to differentiate them:

0x10            //=> 16
0x10.toString() //=> '16'
typeof 0x10     //=> 'number'
typeof 16       //=> 'number'

This would only be possible if you passed the literal as a string:

function isHex(num) {
  return Boolean(num.match(/^0x[0-9a-f]+$/i))
}

isHex('0x1a') //=> true
isHex('16')   //=> false

Upvotes: 12

Oriol
Oriol

Reputation: 288100

You can't. Your number literal is parsed to a number value before being passed to the function. The function only receives the a 64-bit number value which represents e.g. 13, but it can't know whether you wrote 13, 13.0, 0b1101, 0xd or 0o15, or even more complex expressions like 26 / 2 or 10+3.

This kind of information is not exposed in JavaScript. The only way you might manage to do it would be getting the source code of your script, and using your own JS parser.

Alternatively, consider passing a string instead.

Upvotes: 2

deceze
deceze

Reputation: 522076

The option to type numbers in hexadecimal or octal notation besides decimal notation is merely a syntax affordance. You're not creating any sort of different numerical value. 0x0D (hexadecimal) is exactly the same numerical value as 13 (decimal) is exactly the same as 015 (octal). Merely their notation differs by their radix. It is sometimes convenient to work with numbers in different radices, it doesn't change the actual number.

Long story short: you can't tell the difference.

Upvotes: 3

Madara's Ghost
Madara's Ghost

Reputation: 174957

JavaScript cannot tell you how a value of any type was achieved. Much like you can't reach from 12 back to 6+6 or 3*4. 0x0d and 12 are the exact same value.

Upvotes: 3

Related Questions