>>按位运算符未按预期工作

时间:2014-08-19 20:29:52

标签: javascript angularjs bit-manipulation bitwise-operators

我正在尝试为自己创建一个简单的实用程序,以便能够将值从rgb转换为十六进制,反之亦然。除了一个缺陷外,它大部分都有效。

如果我输入类似'007aff'的十六进制值,'00'会被裁剪,结果为'7aff'。 r / g / b /仍然得到正确的值,但我不希望从十六进制值中修剪零。我做错了吗?

// for anyone unfamiliar with angular
// $watch runs when the variable in quotes changes in value
// the rest is basic javascript

AngularJS:

  $scope.$watch('hex', function() {

    var rgb = parseInt($scope.hex, 16);

    $scope.r = (rgb >> 16) & 0xFF;
    $scope.g = (rgb >> 8) & 0xFF;
    $scope.b = rgb & 0xFF;

    $scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';

  });

  $scope.$watch('r+g+b', function() {

    $scope.rgb = 'rgb(' + $scope.r + ',' + $scope.g + ',' + $scope.b + ');';
    $scope.hex = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b).toString(16);
  });

Here is a sample Plunker:

2 个答案:

答案 0 :(得分:1)

00没有直接修剪。将rgb 数字转换为字符串时,不要使用前导零格式化它。

尝试使用前导零格式化:

var value = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b);
$scope.hex = ('000000' + value.toString(16)).slice(-6);

答案 1 :(得分:0)

后:

$scope.hex = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b).toString(16);

添加以下行:

var len = $scope.hex.length;
for ( var i = 0 ; i < 6 - len ; i++ ) {
  $scope.hex = '0' + $scope.hex;
}
相关问题