Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a random color in HEX format with Pascal

2 Answers

0 votes
program RandomHexColor;

function GenerateRandomHexColor: string;
const
  HexChars: array[0..15] of char = ('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
var
  i: integer;
  hex: string;
begin
  hex := '';
  for i := 1 to 6 do
    hex := hex + HexChars[random(16)];
  GenerateRandomHexColor := hex;
end;

begin
  Randomize;  // Seed the random number generator 
  writeln('Random HEX Color: #', GenerateRandomHexColor);
end.



(*
run:

Random HEX Color: #ABB747

*)



 



answered Oct 9, 2025 by avibootz
0 votes
program RandomHexColor;

{$mode delphi}{$H+}

{
    Generate a random color in HEX format (#RRGGBB).
    This program demonstrates how numbers and bits are used
    to produce a valid 24‑bit color value.
}

uses
  SysUtils;  { Provides Format() and other utilities }

{
  Create a 24‑bit random integer (0x000000–0xFFFFFF).
  Random() returns a floating‑point number in [0, 1),
  so multiplying by $1000000 (2^24) gives a full 24‑bit range.
}
function RandomColorInt: LongInt;
begin
  { 24 bits → values from 0 to 16,777,215 (0xFFFFFF) }
  Result := Trunc(Random * $1000000);
end;

{
  Convert a 24‑bit integer into a hex color string.
  Format('%0.6X') ensures exactly 6 uppercase hex digits.
}
function IntToHexColor(Value: LongInt): String;
begin
  Result := '#' + Format('%0.6X', [Value]);
end;

{
  Produce a random hex color by combining the two functions.
}
procedure GenerateRandomHexColor(var Value: LongInt; var Hex: String);
begin
  Value := RandomColorInt;     { 24‑bit random number }
  Hex := IntToHexColor(Value); { Convert to #RRGGBB }
end;

var
  Value: LongInt;
  HexColor: String;

begin
  Randomize;  { Seed the RNG }

  GenerateRandomHexColor(Value, HexColor);

  WriteLn('Random 24‑bit value: ', Value);
  WriteLn('Hex color: ', HexColor);
end.


{
run:

Random 24‑bit value: 12117313
Hex color: #B8E541

}

 



answered 1 day ago by avibootz
...