Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Convert a hexadecimal encoded String to a hexadecimal byte

Now I have to convert the hexadecimal encoded in a String to a byte hexadecimal.

var str = "5e" 

var b = // Should be 0x5e then.

if str = "6b", then b = 0x6b and so on.

Is there any function in javascript, like in java

Byte.parseByte(str, 16)

Thanks in advance

like image 923
user3898336 Avatar asked Nov 28 '25 15:11

user3898336


2 Answers

The function you want is parseInt

parseInt("6b", 16) // returns 107

The first argument to parseInt is a string representation of the number and the second argument is the base. Use 10 for decimal and 16 for hexadecimal.

like image 85
hugomg Avatar answered Dec 01 '25 04:12

hugomg


From your comment, if you expect "an output of 0x6b" from the string "6b" then just prepend "0x" to your string, and further manipulate as you need. There is no Javascript type that will output a hexadecimal in a readable format that you'll see prefixed with '0x' other than a string.

like image 28
Zack Avatar answered Dec 01 '25 03:12

Zack