My goal is to develop a simple tool for myself that can convert values between rgb and hex formats. It's mostly working fine, but there is one issue that I have encountered.
When I input a hex value like '007aff'
, the leading '00'
gets removed and the resulting value is '7aff'
. While the r/g/b values are correct, I do not want the zeroes to be trimmed from the hexadecimal value. Is there something wrong with my approach?
// For those unfamiliar with angular
// $watch triggers when the variable in quotes changes its value
// The rest of the code is basic javascript
AngularJS:
$scope.$watch('hex', function() {
var rgb = parseInt($scope.hex, 16);
$scope.r = (rgb >> 16) & OxFF;
$scope.g = (rgb >> 8) & OxFF;
$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);
});