Buffer.byteLength(字符串,编码方式)计算指定字符串的字节数

本文通过示例代码介绍了如何使用不同的字符编码(如UTF-8、UTF-16LE、Base64、Hex)来统计特定字符串的字节数。展示了在Node.js环境中,对于同一字符串,采用不同编码方式时其占用字节数的变化。

1、问题背景

根据不同的编码方法,统计字符串的字节数


2、实现源码

> dong='您好,世界!';
'您好,世界!'
> dong.length;
6
> Buffer.byteLength(dong,'utf8');
18
> Buffer.byteLength(dong,'utf16le');
12
> Buffer.byteLength(dong,'base64');
4
> Buffer.byteLength(dong,'hex');
3
>


diff --git a/packages/arch-player/src/loader/http/http.ts b/packages/arch-player/src/loader/http/http.ts index 7713022dd..810266f8b 100644 --- a/packages/arch-player/src/loader/http/http.ts +++ b/packages/arch-player/src/loader/http/http.ts @@ -16,6 +16,9 @@ export class HttpLoader extends BaseLoader { private fetchSuccessHook?: FetchSuccessCallback private dataReadyHook?: DataReadyCallback private authenticateHook?: AuthenticateCallback + private _cacheBuffer: Uint8Array = new Uint8Array(0) + private _baseTime: number = performance.now() + private _timeList: [number, number][] = [] private stashBuffer: Uint8Array = new Uint8Array(0) @@ -146,6 +149,22 @@ export class HttpLoader extends BaseLoader { const newBuffer = mergeUint8Array(this.stashBuffer, new Uint8Array(buffer)) const consumed = this.dataReadyHook(newBuffer.buffer) + if (this._cacheBuffer.byteLength === 0) { + this._timeList.push([0, consumed]) + this._baseTime = performance.now() + } else { + this._timeList.push([performance.now() - this._baseTime, consumed]) + } + + this._cacheBuffer = mergeUint8Array(this._cacheBuffer, new Uint8Array(newBuffer.buffer, 0, consumed)) + console.log(this._cacheBuffer.byteLength, this._cacheBuffer.buffer.byteLength) + + if (this._cacheBuffer.byteLength > 1 * 1024 * 1024) { + this.download(this._cacheBuffer.buffer, 'test.buffer') + this.download(JSON.stringify(this._timeList), 'time.json') + this._cacheBuffer = new Uint8Array(0) + } + if (consumed < newBuffer.byteLength) { this.stashBuffer = new Uint8Array(newBuffer.buffer, consumed) } else { @@ -153,6 +172,19 @@ export class HttpLoader extends BaseLoader { } } + download(data: ArrayBuffer | string, name: string) { + const link = document.createElement('a') + const fullBlob = new Blob([data]) + const downloadUrl = window.URL.createObjectURL(fullBlob) + link.style.display = 'none' + link.href = downloadUrl + link.download = name + document.body.appendChild(link) + + link.click() + link.remove() + } + send() {} 分析上述代码的作用
最新发布
08-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值