ktretyak ktretyak - 1 year ago 138
Node.js Question

Method `crypto.randomBytes()` in Node.js generates more bytes than specify in parameter `size`?

I have Node.js v6.3.1. Why the next code generates two characters instead of one?

crypto.randomBytes( 1 ).toString('hex')

Is one byte encodes two characters? Is it possible bug? (docs for randomBytes())

Answer Source

One byte is expressed in hexadecimal encoding as two characters, each in the range of 0-9a-f (upper or lower case). Each characters represents 4-bits.

Hexadecimal (hex) is generally used to represent binary data, some or most 8-bit values, depending on the character encoding, can not be represented as printable characters. As an example the byte with the bits 00000111 is represented as 07 in hex, it is the bell character so it can't print.

See Hexadecimal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download