// Buffer实例化的结果是什么?是字符编码的序列,序列有两种方式,一个是16进制,一个是10进制
// 转成字符串的方法
// 1. buf.toString()
// 2. 字符串拼接:'' + buf
function BufferStudy() {
const data = '2MHN000986'
const buf = Buffer.from(data) // 转成buffer序列
console.log('10进制序列号:', buf)
console.log('打印实例化后的buf:', JSON.stringify(buf)) // 不能用 文字+buf,这样会输出为string类型
// 如果直接使用,输出的是字符编码的十进制序列
for (let k = 0; k < buf.length; k++) {
// console.log('buf当前值:', buf[k])
const char = String.fromCharCode(buf[k])
console.log('当前字符:', char)
}
// 判断是否是buffer类型
const isBuffer = Buffer.isBuffer(buf)
console.log('是否是buffer类型:' + isBuffer)
// 编译为字符串
const bufStr = buf.toString()
console.log('buffer输出为字符串:', bufStr)
for (let j = 0; j < bufStr.length; j++) {
// console.log('字符串当前值:', bufStr[j])
}
// 查看16进制序列
const bufHex = buf.toString('hex')
console.log('16进制序列号:', bufHex)
for (let i = 0; i < bufHex.length; i++) {
// 此时是16进制的
if (i % 2 === 0) {
let charHex = bufHex.slice(i, i + 2)
const dec = parseInt(charHex, 16)
const word = String.fromCharCode(dec)
console.log(word, '字符-->')
}
// console.log('16进制当前值:', bufHex[i])
}
}
BufferStudy()