rgb to hex

This commit is contained in:
Alexander Popov 2023-05-14 15:50:24 +03:00
parent 2fc7bbe908
commit 7539e9d5ab
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
1 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,90 @@
---
title: "🔰 Преобразование цвета RGB в HEX на Си"
date: 2023-05-14T15:50:00+03:00
draft: false
tags: [c, tips]
---
## Примеры преобразования RGB в HEX и обратно
Код очень простой. Выкладываю пример, остальное сами.
## RGB -> HEX
Значение аргумента `0` в функции `printf()` — красный цвет.
`128` — зелёный цвет и `64` — синий цвет.
```c
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("#%.2x%.2x%.2x\n", 0, 128, 64);
return 0;
}
```
## HEX -> RGB
### Пример № 1
Очень простой пример. Строка `primary_color` хранит значение цвета.
Функцией `sscanf()` разбиваем её на три значения:
- `r` — красный цвет.
- `g` — зелёный цвет.
- `b` — синий цвет.
```c
#include <stdio.h>
int main(int argc, char const *argv[])
{
char *primary_color = "0000FF";
int r, g, b;
sscanf(primary_color, "%02x%02x%02x", &r, &g, &b);
printf("%d, %d, %d\n", r, g, b);
}
```
### Пример № 2
```c
#include <stdio.h>
int main(int argc, char const *argv[])
{
int secondary_color = 0x32011E;
double dR, dG, dB;
dR = ((secondary_color >> 16) & 0xff);
dG = ((secondary_color >> 8) & 0xFF);
dB = ((secondary_color) & 0xFF);
printf("%.lf, %.lf, %.lf\n", dR, dG, dB);
}
```
И тоже самое, но с некоторыми отличиями.
```c
#include <stdio.h>
int main(int argc, char const *argv[])
{
int secondary_color = 0x32011E;
double dR, dG, dB;
dR = ((secondary_color >> 16) & 0xff) / 255.0;
dG = ((secondary_color >> 8) & 0xFF) / 255.0;
dB = ((secondary_color) & 0xFF) / 255.0;
printf("%.lf, %.lf, %.lf\n", dR * 255, dG * 255, dB * 255);
}
```