如何将十六进制数字压缩成短字符串?

时间:2016-11-07 17:41:21

标签: javascript encoding hex compression converter

我有一个未知长度的十六进制数,我想将其转换为尽可能短的字符串。然后能够将新字符串转换回原始数字。

由于每个数字仅在4位上,我想将数字转换为UFT-16或UFT-32字符串。这将创建一个带有奇怪字符的短字符串。

假设示例:0x874FAB41900C - > “ÚΔЂ” - > 0x874FAB41900C。

所以我正在寻找的是两个类似的Javascript函数:

function hexToString(hex) {
    for (var i=0; i < hex.length; i++) {
        // convert the digits into UFT-16
    }

    return string;
}

function stringToHex(string) {
    for (var i=0; i < string.length; i++) {
        // convert the char back into hex values
    }

    return hex;
}

知道怎么做吗?

1 个答案:

答案 0 :(得分:4)

在js字符串中,字符使用16位,因此我们可以在1:

中打包4个十六进制字符

function hexToString(hex) {
  hex = hex.substring(2) // remove the '0x' part
  var string = ""

  while (hex.length % 4 != 0) { // we need it to be multiple of 4
    hex =  "0" + hex;
  }

  for (var i = 0; i < hex.length; i+= 4){
    string += String.fromCharCode(parseInt(hex.substring(i,i + 4), 16)) // get char from ascii code which goes from 0 to 65536
  }

  return string;
}

function stringToHex(string) {
  var hex = ""
  for (var i=0; i < string.length; i++) {
    hex += ( (i == 0 ? "" : "000") + string.charCodeAt(i).toString(16)).slice(-4) // get character ascii code and convert to hexa string, adding necessary 0s
  }

  return '0x' + hex.toUpperCase();
}



var str = hexToString("0x874FAB41900C")
console.log(str)
console.log(stringToHex(str))

如果您需要32位版本,则需要更改编码版本,解码保持不变。请注意,只有21位的unicode字符,所以不要认为你可以做得比16位更好,这个不会真正使用更少的字符:

function hexToString(hex) {
  hex = hex.substring(2) // remove the '0x' part
  var string = ""

  while (hex.length % 8 != 0) { // we need it to be multiple of 8
    hex =  "0" + hex;
  }

  for (var i = 0; i < hex.length; i+= 8){
    string += String.fromCharCode(parseInt(hex.substring(i,i + 4), 16), parseInt(hex.substring(i + 4,i + 8), 16))
  }

  return string;
}

您可以在此处详细了解32位:how to render 32bit unicode characters in google v8 (and nodejs)

编辑:一个有趣的例子

function hexToString(hex) {
  hex = hex.substring(2) // remove the '0x' part
  var string = ""

  while (hex.length % 8 != 0) { // we need it to be multiple of 8
    hex =  "0" + hex;
  }

  for (var i = 0; i < hex.length; i+= 8){
    string += String.fromCharCode(parseInt(hex.substring(i,i + 4), 16), parseInt(hex.substring(i + 4,i + 8), 16))
  }

  return string;
}

console.log(hexToString("0xD83DDCA3"))