簡體   English   中英

>>按位運算符未按預期工作

[英]>> bitwise operator not working as expected

我正在嘗試為自己創建一個簡單的實用程序,以便能夠將值從rgb轉換為十六進制,反之亦然。 除一個缺陷外,它在大多數情況下都有效。

如果我輸入類似'007aff'的十六進制值'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);
  });

這是一個示例柱塞:

00不直接修剪 將RGB 數字轉換為字符串時,請勿使用前導零對其進行格式化。

嘗試使用以下格式格式化前導零:

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

后:

$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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM