javascript中字节数组到十六进制字符串的转换 [英] Byte array to Hex string conversion in javascript

查看:454
本文介绍了javascript中字节数组到十六进制字符串的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 [4,-101,122,-41,-30,23,-28,3,..] 形式的字节数组,我想将其转换为 6d69f597b217fa333246c2c8我正在使用以下功能

function toHexString(bytes) {返回字节映射(函数(字节){返回(字节和 0xFF).toString(16)}).加入('')}

这给了我一个相同形式的字符串,但我怀疑它不是一个有效的转换,因为十六进制字符串比预期的要短一些.我认为翻译应该得到0a10a6dc".请告诉我我是否错了或者这是一个正确的转换,但也许我没有使用正确的字节数组

字节数组 4,-127,45,126,58,-104,41,-27,-43,27,-35,100,-50,-77,93,-16,96,105,-101,-63,48,-105,49,-67,110,111,26,84,67,-89,-7,-50,10,-12,56,47,-49,-42,-11,-8,-96,-117,-78,97,-105,9,-62,-44,-97,-73,113,96,23,112,-14,-62,103,-104,90,-14,117,78,31,-116,-7

对应转换4812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ceaf4382fcfd6f5f8a08bb261979c77fc8c5c27f408c5c27fc8fc5c807fc8c50c7f8c50c8097f9

解决方案

您缺少十六进制转换中的填充.你会想要使用

function toHexString(byteArray) {返回 Array.from(byteArray, function(byte) {return ('0' + (byte & 0xFF).toString(16)).slice(-2);}).加入('')}

以便每个字节转换为正好两个十六进制数字.您的预期输出将是 04812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ce0af4382fcfd6f5f8a08bb2619709b77f4709c27f98c50c7f9f8c50c5c8c5c8c5c8fc8c50c7f9f

I have a byte array of the form [4,-101,122,-41,-30,23,-28,3,..] which I want to convert in the form 6d69f597b217fa333246c2c8 I'm using below function

function toHexString(bytes) {
  return bytes.map(function(byte) {
    return (byte & 0xFF).toString(16)
  }).join('')
}

which is giving me a string of the same form but I suspect that it's not an efficient conversion because the hex string is bit shorter than expected. I think translating should get "0a10a6dc". Please tell me if I'm wrong or is this a right conversion but maybe I'm not using the right byte array

byte array 4,-127,45,126,58,-104,41,-27,-43,27,-35,100,-50,-77,93,-16,96,105,-101,-63,48,-105,49,-67,110,111,26,84,67,-89,-7,-50,10,-12,56,47,-49,-42,-11,-8,-96,-117,-78,97,-105,9,-62,-44,-97,-73,113,96,23,112,-14,-62,103,-104,90,-14,117,78,31,-116,-7

Corresponding conversion 4812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ceaf4382fcfd6f5f8a08bb261979c2d49fb771601770f2c267985af2754e1f8cf9

解决方案

You are missing the padding in the hex conversion. You'll want to use

function toHexString(byteArray) {
  return Array.from(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('')
}

so that each byte transforms to exactly two hex digits. Your expected output would be 04812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ce0af4382fcfd6f5f8a08bb2619709c2d49fb771601770f2c267985af2754e1f8cf9

这篇关于javascript中字节数组到十六进制字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆