在Javascript中更容易处理十六进制字符串和十六进制值 [英] Working with hex strings and hex values more easily in Javascript

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

问题描述

我使用表示十六进制数字(实际上是十六进制颜色)并添加它们的字符串。所以,加入 aaaaaa + 010101 = ababab 。我的方法似乎不必要的冗长和复杂:

I am taking strings which represent hexadecimal numbers (actually, hex colors) and adding them. So, adding aaaaaa + 010101 = ababab. 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'




  • (JsFiddle:http://jsfiddle.net/U92vt/1/

    • (JsFiddle: http://jsfiddle.net/U92vt/1/)
    • 在连接 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, 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 as well, 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 way to do this with less steps! (And I don't mean just putting it all on one line (parseInt("0x"+"aaaaaa",16)+0x010101).toString(16) or using shorthand, I mean actually doing less operations.)

      有什么方法可以让JavaScript停止对所有数学运算使用小数,并使用十六进制代替?还是有其他一些方法让Javascript更容易使用Hex?

      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 Javascript 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天全站免登陆