Thread: How to split an int, into 2-Bytes???? Controlling PWM with an int.

  1. #1
    Registered User
    Join Date
    Oct 2013

    How to split an int, into 2-Bytes???? Controlling PWM with an int.

    Hey guys.
    Im using some motors which run off PWM pins.
    Theres a High byte and Loq byte register (PWMH,PWML).

    I have an int which i need to put into these registers but i dont know how???
    so for example
    int:84 -> PWMH=0x00 , PWML=0x54
    int:310 -> PWMH=0x01 , PWML=0x36
    int:11588 -> PWMH=0x2D , PWML=0x44

    Appreciate any help

  2. #2
    Registered User
    Join Date
    Jun 2011
    You can use bit-wise operators to mask the upper and lower bytes separately and assign the results to your registers (the masked upper byte would require a shift to get the bits in the correct position).

  3. #3
    11DE784A SirPrattlepod's Avatar
    Join Date
    Aug 2013
    Expanding on Matticus's post, which really has enough information, but anyway...

    Given the (base 10) number 11588, this is 0x2D44 when represented in hexadecimal. When the number is expressed using hexadecimal the operations you need to undertake become much clearer (in my opinion anyway). One hex digit is 4-bits, and 2 hex digits are 4 bits (this never changes and is why hex <--> binary conversions can easily be done in your head).

    Okay, so you need to split 0x2D44 into two "bytes": 0x2D and 0x44

    The numbers are "combined", though: 0xhhll where hh is the "high byte" and ll is the "low byte".

    To get the low byte, you mask the bits that you're not interested in using a bitwise AND; i.e. anything other than the 'll' bits (0xFF) you want to get rid of.

    The high byte is, well, those in the 'hh' position so mask with 0xFF00. They are in the wrong position, though... so you need to shift them to the right. I'll leave it you to work out the number of right shifts required because there is more than enough position in this post to determine that.

    Just a quick note, I am using the word "byte" very liberally when I've used it in this comment. In C a char is always 1 byte. But be careful because the number of bits in the byte is not necessarily 8 (the number of bits must be >= 8)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. split strings (and split thread)
    By mahi in forum C Programming
    Replies: 1
    Last Post: 10-31-2011, 06:56 AM
  2. working set, virtual bytes and private bytes
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 01-10-2008, 02:39 AM
  3. controlling software help
    By mramazing in forum C++ Programming
    Replies: 1
    Last Post: 10-15-2007, 07:53 PM
  4. controlling how many bytes a variable takes up
    By mike_532532 in forum C++ Programming
    Replies: 6
    Last Post: 07-30-2007, 04:20 AM
  5. Controlling ports
    By lockpatrick in forum Linux Programming
    Replies: 2
    Last Post: 06-09-2002, 11:58 AM