Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you extract digits from number?

I asked similar question before but the answers weren't exactly what I was looking for, so this time I will provide more details.

I am programming a microcontroller using C language for the first time. I have an Android APP that allows the user to select a combination of colors (RGB colors) then sends the color code to the microcontroller. The microcontroller displays the light based on what was chosen.

What I am attempting to do is to be able to read the number by four digits at a time. So if the number that was sent is 2005001000200 I would like to do the following.

Extract the first digit and save it in a variable called mode ..Then.. Extract the next four digits and save them in a variable called red ..Then... Extract the next four digits and save them in a variable called green ..Then.. extract the last four digits and save them in a variable called blue. So the output should be like this ...

Mode = 2

Red = 0050

Green = 0100

Blue = 0200

If I can see an example illustrating what I am trying to do that would be awesome. Please keep in mind I am programming a microcontroller for the first time. Thank you so much!

like image 335
Ammar Avatar asked Nov 20 '25 17:11

Ammar


1 Answers

Supposing I had 2005001000200ULL in an unsigned long long somewhere:

unsigned long long value = 2005001000200ULL;

If I wanted to extract blue, I'd use a modulo operation:

unsigned long long value = 2005001000200ULL;
unsigned int blue = value % 10000;

To extract green, I'd use a division operation, followed by the same modulo operation:

unsigned long long value = 2005001000200ULL;
unsigned int blue = value % 10000; value /= 10000;
unsigned int green = value % 10000;

To extract red, repeat the process:

...

unsigned long long value = 2005001000200ULL;
unsigned int blue = value % 10000; value /= 10000;
unsigned int green = value % 10000; value /= 10000;
unsigned int red = value % 10000; value /= 10000;
unsigned int mode = value;

Hey! I missed a step! :(

like image 158
autistic Avatar answered Nov 23 '25 05:11

autistic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!