Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting numeric data types in C
    primarykey
    data
    text
    <p>I saw this <a href="https://stackoverflow.com/questions/1942159/need-some-clarification-regarding-casting-in-c">question</a> on SO about casting, and the answer specifically mentioned numeric types. I thought I understood this till now, when I have to do it.</p> <p>I have two int's I want to add, divide by two and save to another int. So I create a temporary variable called 'bucket' that's one datatype bigger, add the two ints and shift right by one.</p> <p>I've come up with several ways to do this, all seem to work, but several are, I think, unnecessary. Please look this over and let me know where I misunderstood K&amp;R.</p> <p>Case1:</p> <pre><code>bucket = ( (long) ADCBUF0 + (long) ADCBUF7) &gt;&gt; 1; rem_volt = bucket; </code></pre> <p>Case 2:</p> <pre><code>bucket = ( (long) ADCBUF1 + (long) ADCBUF8) &gt;&gt; 1; loc_volt = (unsigned int) bucket; </code></pre> <p>Case 3:</p> <pre><code>bucket = (long) ADCBUF2 + (long) ADCBUF9; current = (unsigned int) (bucket &gt;&gt; 1); </code></pre> <p>Case 4:</p> <pre><code>bucket = ADCBUF3 + ADCBUFA; dac_A = (unsigned int) (bucket &gt;&gt; 1); </code></pre> <p>Case 5:</p> <pre><code>bucket = (long) (ADCBUF4 + ADCBUFB) &gt;&gt; 1; dac_B = (unsigned int) bucket; </code></pre> <p>I think Case 4 or Case 5 is the correct way to do this, since Case 1 implicitly casts a long to an int, Case 2 I think is right, but more typing, Case 3 I think uneccessarily casts the ints to longs when only their sum needs to be cast.</p> <p>Thanks for your thoughts.</p> <p>EDIT: Thanks for the comments so far! To clarify, I am being sloppy about the unsigned vs signed, they should all be unsigned. I am trying to avoid an overflow on the addition. My long is 2 bytes bigger than my int. (So it's really much bigger than needed, I could just check the overflow bit.) I'm working on an embedded platform, I will never port this (I swear!) but I am trying to consider whomever comes after me and tries to puzzle out what I'm doing, so I'll use the divide by 2 rather than the bitshift.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload