Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transfer: ArrayBuffer、Base64、Hex、String #1

Open
54leibo opened this issue Jun 25, 2019 · 0 comments
Open

Transfer: ArrayBuffer、Base64、Hex、String #1

54leibo opened this issue Jun 25, 2019 · 0 comments

Comments

@54leibo
Copy link
Owner

54leibo commented Jun 25, 2019

  • ArrayBuffer <=> String:
const _arrayBufferToString = arrayBuffer => 
    String.fromCharCode(...new Uint16Array(arrayBuffer))

const _stringToArrayBuffer = str => 
    Uint16Array.from(str, c => c.charCodeAt(0)).buffer

// example
const str = '123'
const buf = _stringToArrayBuffer(str)
console.log(str, _arrayBufferToString(buf))
  • ArrayBuffer <=> Base64
const _arrayBufferToBase64 = arrayBuffer => 
    btoa(String.fromCharCode(...new Uint16Array(arrayBuffer)))

const _base64ToArrayBuffer = base64 => 
    Uint16Array.from(atob(base64), c => c.charCodeAt(0)).buffer
    
// example
const base64 = window.btoa('123')
const buf = _base64ToArrayBuffer(base64)
console.log(base64, _arrayBufferToBase64(buf))
  • ArrayBuffer <=> Hex
const _arrayBufferToHex = (arrayBuffer) => 
    Array.prototype.map.call(new Uint16Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('')

const _hexToArrayBuffer = (str) => {
    const len = str.length
    const arrayBuffer = new ArrayBuffer(len)
    const uint16 = new Uint16Array(arrayBuffer)
    let b;
    
    for (let i=0, j=0; i<len; i+=2) {
        b = parseInt(str.substring(i, i+2), 16)
        uint16[j++] = b
    }
    
    return arrayBuffer;
}

// example
const hex = "39b2abc192db9bc9175de7e5f9e7ef08"
const buffer = _hexToArrayBuffer(hex);
console.log(hex, _arrayBufferToHex(buffer), hex === _arrayBufferToHex(buffer))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant