I know that this line of code: Buffer.from('key', 'hex') Converts a string into its binary representation. My question is: what does adding the 'hex' at the end do? I am confused, since the key is already in hexa-decimal, why would we want to specify that if the function can work on any string?


A string can consist of an integer in any basis, that's the reason you have to include the basis, so the integer within is interpreted properly. Examples:

'01' Basis 2, or 'binary'

'01234567' Basis 8, or 'octal',

'0123456789' Basis 10, or 'decimal',

'0123456789ABCDEF' Basis 16, or 'hexadecimal'

Example that shows why it is important to specify the representation:

We want to intepret the following number as an octal number: 42

Buffer(42, 5) would create a byte array from the number 2210

Buffer(42, 8) would create a byte array from the number 3410

Buffer(42, 10) would (obviously) create a byte array from the number 4210

note that the string representation for the basis can differ in the Buffer API ('hexadecimal' is only 'hex' in Buffer), checkout the Buffer documentation for more information (https://nodejs.org/api/buffer.html)

btw. please post only Ethereum related questions in this stackexchange, use stackoverflow for language specific questions.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.