PHP's bin2hex in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { bin2hex } from 'locutus/php/strings/bin2hex'.

Or with CommonJS: const { bin2hex } = require('locutus/php/strings/bin2hex')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1bin2hex('Kev')'4b6576'
2bin2hex(String.fromCharCode(0x00))'00'
3bin2hex("æ")'c3a6'

Here's what our current TypeScript equivalent to PHP's bin2hex looks like.

export function bin2hex(s: string): string {
// discuss at: https://locutus.io/php/bin2hex/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// bugfixed by: Linuxworld
// improved by: ntoniazzi (https://locutus.io/php/bin2hex:361#comment_177616)
// example 1: bin2hex('Kev')
// returns 1: '4b6576'
// example 2: bin2hex(String.fromCharCode(0x00))
// returns 2: '00'
// example 3: bin2hex("æ")
// returns 3: 'c3a6'

const encoder = new TextEncoder()
const bytes = encoder.encode(s)
let hex = ''
for (const byte of bytes) {
hex += byte.toString(16).padStart(2, '0')
}
return hex
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star