Jump to content
Sign in to follow this  

parseInt question

Recommended Posts

the function below calculates the relative brightness of a colour (specified in hex : #008080 = 'teal')

    //funtion to find the relative brightness of a colour (hex-code)
    function Brightness(colour: string): integer;
      function coloro(color) {
        var R =	parseInt(color.substring(0,2),16);
        var G =	parseInt(color.substring(2,4),16);
        var B =	parseInt(color.substring(4,6),16);
        return Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
      @result = coloro(colour);

and is used to determine the best text colour on specific backgrounds (brightness < 130 = white else black);

Not unlike the ColorListBox project in featured demo's. The above algorithm is a bit different than that demo and supposedly more accurate.

Function works well but I don't like the asm block. Does anyone know if there is a Delphi/Pascal routine available somewhere which does the same as the javascript parseInt function ?


Share this post

Link to post
Share on other sites
function Brightness(colour: Variant): Float;
  function coloro(color: Variant): Float;
    R, G, B: Integer;
    function parseInt(s: Variant{String}; radix: integer = 0): integer; external "parseInt";
    if(color.length=7) then color:= color.substring(1);
    R :=	parseInt(color.substring(0,2), 16);
    G :=	parseInt(color.substring(2,4), 16);
    B :=	parseInt(color.substring(4,6), 16);
    Result := sqrt(R * R * 0.241 + G * G * 0.691 + B * B * 0.068);
  Result := coloro(colour);


Share this post

Link to post
Share on other sites

I was about to write that the snippet simply copies 2 by 2 hex characters and then converts that to an integer number.
In pure pascal it would be a bit messy since pascal's StrToInt doesnt support hex (unless prefixed by $).
ASM sections are very much needed, they might not be pretty (not too fond on them myself) but there are some fundamental code sections that would never work if we used pascal only. Speed is also a factor to keep in mind, especially for procedures that you will call many times.

But you seem all set so i'll leave you to it! Happy coding!

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this