SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    perfect = good enough peach's Avatar
    Join Date
    Jun 2004
    Location
    -Netherlands-
    Posts
    1,384
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    dont understand complex php syntax

    I've looked at this code a number of times already but I still don't really get it:
    PHP Code:
    /**
     * Convert an RGB triplet to a hex color.
     */
    function _color_pack($rgb$normalize false) {
      foreach (
    $rgb as $k => $v) {
        
    $out |= (($v * ($normalize 255 1)) << (16 $k 8));
      }
      return 
    '#'str_pad(dechex($out), 60STR_PAD_LEFT);

    What I don't get is what the third line is doing, beginning with the |= part that means bitshift I think but Im not sure.
    Can anyone explain what steps this code takes logically to turn an RGB triplet into a hex code?

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Try looking at it in an expanded form:
    PHP Code:
    function _color_pack($rgb$normalize false) {
        
    $out 0;
        foreach (
    $rgb as $key => $value){
            
    $OR 0;
            if(
    $normalize){
                
    $OR $value 255;
            }else{
                
    $OR $value;
            }
            
    $OR $OR << (16 $key 8);
            
    $out $out $OR;
        }
        return 
    '#'str_pad(dechex($out), 60STR_PAD_LEFT);

    Are you familiar with binary theory? I.e. 5 | 3 = 7 etc.

    If so, here are PHP's bitwise operators

    (note: $A |= $X is the same thing as $A = $A | $X)

    If not, just say so and me or some other member will try to help you understand it.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •