3

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

3
  • 1
    b = parseInt('5e', 16) Commented Aug 20, 2016 at 6:17
  • You can use Int8Array (signed) or Uint8Array (unsigned) types with the native function parseInt(hexString, 16) Commented Aug 20, 2016 at 6:19
  • 1
    What is a "hexadecimal byte"? Commented Aug 20, 2016 at 7:06

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

No, it gives the value 107
0x6b is just another way to write 107
Use Int8Array or Uint8Array to store as byte.
The problem is that I expect an output of 0x6b which can be used to pass as a buffer.
I don't understand. In Javascript (and most other programming languages), 0x6b is just another way to write 107. They are the same thing.
1

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.

Comments

1

I solved it by using just

new Buffer("32476832", 'hex')

this solved my problem and gave me the desired buffer

<Buffer 32 47 68 32>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.