Reputation: 5089
I'm trying to create a simple utility for myself to be able to convert values from rgb to hex, and vice versa. It works for the most part, except for one flaw.
If I enter a hex value like '007aff'
, '00'
gets trimmed and the result is '7aff'
. The r/g/b/ still gets the correct value, but I don't want the zeroes trimmed from the hexadecimal value. Am I doing something incorrectly?
// 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);
});
Upvotes: 0
Views: 143
Reputation: 56616
After:
$scope.hex = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b).toString(16);
add the following lines:
var len = $scope.hex.length;
for ( var i = 0 ; i < 6 - len ; i++ ) {
$scope.hex = '0' + $scope.hex;
}
Upvotes: 0
Reputation: 4339
The 00
aren't directly trimmed. When your convert the rgb number to a string, you don't format it with leading zeros.
Try this to format with leading zeros:
var value = parseInt($scope.r << 16 | $scope.g << 8 | $scope.b);
$scope.hex = ('000000' + value.toString(16)).slice(-6);
Upvotes: 1