Converting uint16_t to uint8_t

Go To Last Post
8 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Some 16-bit number cumputes in my program, and then it must be written into OCR1A 8-bit register. So, I need to convert uint16_t to uint8_t.

uint16_t A = 120;
uint8_t B;

Simple B = A doesn't work.

Naturally, I need lower part of 16-bit number.
What should I do?
Thanks :-)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

kreyl wrote:
Simple B = A doesn't work.

Really? It works for me. What does it do, then?

OCR1A = A; will work as long as A <= 255.

Don

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

You can cast it to kill the upper-byte of the 16-bit variable:

uint16_t A = 120;
uint8_t B;

B = (uint8_t)A; // Get lower byte of 16-bit var

If you need the upper byte, shift and cast instead:

uint16_t A = 120;
uint8_t B;

B = (uint8_t)(A >> 8); // Get upper byte of 16-bit var

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

abcminiuser wrote:
You can cast it to kill the upper-byte of the 16-bit variable:

uint16_t A = 120;
uint8_t B;

B = (uint8_t)A; // Get lower byte of 16-bit var

It won't hurt to cast the uint16_t to uint8_t but it's not necessary. A direct assignment will discard the upper-byte.

Don

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Self commenting code. Once bitten twice shy ;).

- Dean :twisted:

Make Atmel Studio better with my free extensions. Open source and feedback welcome!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Removed spam.

Last Edited: Thu. Oct 29, 2015 - 06:54 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Vish, do this one more time and you'll be reported. Its useless digging up old posts just so you can advertise your blog. Just stop it.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

"Experience is what enables you to recognise a mistake the second time you make it."

"Good judgement comes from experience.  Experience comes from bad judgement."

"Wisdom is always wont to arrive late, and to be a little approximate on first possession."

"When you hear hoofbeats, think horses, not unicorns."

"Fast.  Cheap.  Good.  Pick two."

"We see a lot of arses on handlebars around here." - [J Ekdahl]