在 Javascript 中更轻松地使用十六进制字符串和十六进制值 [英] Working with hex strings and hex values more easily in Javascript

查看:31
本文介绍了在 Javascript 中更轻松地使用十六进制字符串和十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,它接受代表十六进制数字的字符串——实际上是十六进制颜色——并将它们相加.例如,添加 aaaaaa010101 给出输出 ababab.
然而,我的方法似乎不必要地冗长和复杂:

I have some code which takes strings representing hexadecimal numbers - hex colors, actually - and adds them. For example, adding aaaaaa and 010101 gives the output ababab.
However, my method seems unnecessarily long and complicated:

var hexValue = "aaaaaa";
hexValue = "0x" + hexValue;
hexValue = parseInt(hexValue, 16);
hexValue = hexValue + 0x010101;
hexValue = hexValue.toString(16);
document.write(hexValue); // outputs 'ababab'

16进制值连接0x后还是字符串,所以那我要改成数字,然后我可以加,然后我要改它返回为十六进制格式!如果我添加的数字是以十六进制字符串开头,或者您考虑到我正在所有这些开始之前从十六进制颜色中删除 # ,则还有更多步骤.

The hex value is still a string after concatenating 0x, so then I have to change it to a number, then I can add, and then I have to change it back into hex format! There are even more steps if the number I'm adding to it is a hexadecimal string to begin with, or if you take into consideration that I am removing the # from the hex color before all this starts.

当然有一种更简单的方法来进行如此简单的十六进制计算!为了清楚起见,我的意思并不是像 (parseInt("0x"+"aaaaaa",16)+0x010101).toString(16) 或使用速记 - 我的意思是实际上做的操作更少.

Surely there's a simpler way to do such simple hexadecimal calculations! And just to be clear, I don't mean just putting it all on one line like (parseInt("0x"+"aaaaaa",16)+0x010101).toString(16) or using shorthand - I mean actually doing less operations.

有什么方法可以让 javascript 停止在所有数学运算中使用十进制,而是使用十六进制?或者有没有其他方法可以让 JS 更轻松地使用十六进制?

Is there some way to get javascript to stop using decimal for all of its mathematical operations and use hex instead? Or is there some other method of making JS work with hex more easily?

推荐答案

不,没有办法告诉 JavaScript 语言默认使用十六进制整数格式而不是十进制.您的代码非常简洁,但请注意,当您将parseInt"与基数一起使用时,您不需要在0x"基数指示符之前加上.

No, there is no way to tell the JavaScript language to use hex integer format instead of decimal by default. Your code is about as concise as it gets but note that you do not need to prepend the "0x" base indicator when you use "parseInt" with a base.

以下是我将如何解决您的问题:

Here is how I would approach your problem:

function addHexColor(c1, c2) {
  var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
  while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
  return hexStr;
}

addHexColor('aaaaaa', '010101'); // => 'ababab'
addHexColor('010101', '010101'); // => '020202'

这篇关于在 Javascript 中更轻松地使用十六进制字符串和十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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