Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Transform decimal to hexadecimal

    Hello,

    I would like to transform a column of RGB colors codes to hexadecimals codes.
    In Excel ther is a function called "DECHEX" I can not find the same thing in Stata.

    For exemple :
    R G B
    180 0 0
    looks like that in hexa
    h1 h2 h3
    B4 00 00
    "#B40000" is the hexadecimal transcription of "180/0/0" in RGB

    Regards.
    Marc

  • #2
    This may help.

    Code:
    *! 1.0.0 NJC 21 January 2021
    program vectortohex, sclass
        quietly foreach i of local 0 {
            capture inbase 16 `i'
            if _rc {
                di as err "something is wrong, but no idea what except that `i' doesn't make sense"
                exit 498
            }
            inbase 16 `i'    
            
            local wanted `wanted' `r(base)'
        }
        
        sreturn local hex "`wanted'"
    end
        
    
    . vectortohex 180 0 0
    
    . sreturn list
    
    macros:
                    s(hex) : "b4 0 0"
                      s(k) : "1"
                s(varlist) : "_variables"
    Last edited by Nick Cox; 21 Jan 2021, 07:04.

    Comment


    • #3
      Interesting question - I learned yet another thing from the solution Nick Cox provides in post #2. Building on it, this is how I would add a column of hex RGB codes to a dataset with separate decimal red, green, and blue color codes.
      Code:
      * Example generated by -dataex-. To install: ssc install dataex
      clear
      input int (r g b)
      180 0 0
      255 255 255
      0 0 0
      0 32 64
      127 63  31
      end
      generate str7 rgb = ""
      forvalues i=1/`c(N)' {
          local c = ( r[`i'] * 256 + g[`i'] ) * 256 + b[`i']
          quietly inbase 16 `c'
          local c = substr("000000`r(base)'",-6,.)
          quietly replace rgb = "#" + "`c'" in `i'
      }
      list
      Code:
      . list
      
           +---------------------------+
           |   r     g     b       rgb |
           |---------------------------|
        1. | 180     0     0   #b40000 |
        2. | 255   255   255   #ffffff |
        3. |   0     0     0   #000000 |
        4. |   0    32    64   #002040 |
        5. | 127    63    31   #7f3f1f |
           +---------------------------+

      Comment


      • #4
        Super !
        Code:
        inbase 16
        thank you both for your answers.
        Last edited by Marc Audrna; 21 Jan 2021, 09:11.

        Comment


        • #5
          I rejoiced too soon... I'm working with Stata IC 13.1...

          macro substitution results in line that is too long
          Last edited by Marc Audrna; 21 Jan 2021, 09:33.

          Comment


          • #6
            You hit "Post Reply" too soon - we can't help you fix code that we cannot see.

            Comment

            Working...
            X