How to find out the negative of a color in hexadecimal?

I would like to know what is the calculation I can use in language like javascript, php or python to find out the negative of a hexadecimal cor.

Example: if negative of white is black, then I assume:

`#FFFFFF => #000000`

Or

 0xFFFFFF => 0x000000
Author: Wallace Maxters, 2015-12-11

3 answers

The inverse color can be calculated via or exclusive (XOR) versus the maximum value (#FFFFFF).

The color format in hexadecimal is already a hint of how to perform this operation: each of the double octets in #RRGGBB represents a primary color, whose intensity can vary from #00 to #FF (255 in decimal).

In other words, each primary color is represented by 8 bits.

To invert a color, invert the bits:

Cor     Valor HEX valor BIN                     BIN invertido                 HEX invertido
Preto   #000000   B00000000 00000000 00000000   B11111111 11111111 11111111   #FFFFFF    
Branco  #FFFFFF   B11111111 11111111 11111111   B00000000 00000000 00000000   #000000
Azul    #0000FF   B00000000 00000000 11111111   B11111111 11111111 00000000   #FFFF00

An example of code in Angular / javaScript that performs this operation follows below:

function SampleController($scope) {
  $scope.sourceValue = 0;
  $scope.inverseColor = function(){
    var srcVal = $scope.sourceValue;
    var valNumerico = parseInt(srcVal, 16);
    var mascara = parseInt('FFFFFF', 16);
    var dest = valNumerico ^ mascara; //Operação XOR
    return dest.toString(16);
  };  
}
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body>
    <div ng-controller="SampleController">
      
      Cor: #<input type='text' ng-model='sourceValue'>
      <br />
      
      Inversa: {{ inverseColor() }}
    </div>
  </body>
</html>
 9
Author: OnoSendai, 2015-12-11 14:12:21

I found an example in PHP:

function color_inverse($color){
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}

Testing:

// preto -> branco
print color_inverse('#000000'); 
// --> retorna #ffffff

Credits: Link

 3
Author: Rafael, 2015-12-11 13:44:53

If it is FOR DISPLAY ONLY you can solve this in CSS

-webkit-filter: invert(100%);
filter: invert(100%);

Via Javascript has the solution in this other question. https://stackoverflow.com/questions/1664140/js-function-to-calculate-complementary-colour

 1
Author: Leandro Angelo, 2017-05-23 12:37:28