Skip to content

[js] 第637天 写一个方法将ArrayBuffer转为字符串 #3429

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第637天 写一个方法将ArrayBuffer转为字符串

#2727

3+1官网

我也要出题

Activity

yuhaihe

yuhaihe commented on Jan 22, 2021

@yuhaihe

let resBlob = new Blob([arraybuffer]) //res为arraybuffer型数据
let reader = new FileReader()
reader.readAsText(resBlob, "utf-8")
reader.onload = () => {
let tmpResObj = JSON.parse(reader.result)
}

NoBey

NoBey commented on Mar 12, 2022

@NoBey

https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@NoBey@yuhaihe

        Issue actions

          [js] 第637天 写一个方法将ArrayBuffer转为字符串 · Issue #3429 · haizlin/fe-interview