Different int sizes on my computer and Arduino

后端 未结 5 496
梦谈多话
梦谈多话 2021-01-21 07:12

Im working on a sparetime project, making some server code to an Arduino Duemilanove, but before I test this code on the controller I am testing it on my own machine (An OS X ba

相关标签:
5条回答
  • 2021-01-21 07:51

    The C standard defines an int as being a signed type large enough to at least hold all integers between -32768 and 32767 - implementations are free to choose larger types, and any modern 32-bit system will choose a 32-bit integer. However, as you've seen, some embedded platforms still use 16-bit ints. I would recommend using uint16_t or uint32_t if your arduino compiler supports it; if not, use preprocessor macros to typedef those types yourself.

    0 讨论(0)
  • 2021-01-21 07:55

    The correct way to handle the situation is to choose the type based on the values it will need to represent:

    • If it's a general small integer, and the range -32767 to 32767 is OK, use int;
    • Otherwise, if the range -2147483647 to 2147483647 is OK, use long;
    • Otherwise, use long long.
    • If the range -32767 to 32767 is OK and space efficiency is important, use short (or signed char, if the range -127 to 127 is OK).

    As long as you have made no other assumptions that these (ie. always using sizeof instead of assuming the width of the type), then your code will be portable.

    In general, you should only need to use the fixed-width types from stdint.h for values that are being exchanged through a binary interface with another system - ie. being read from or written to the network or a file.

    0 讨论(0)
  • 2021-01-21 07:58

    Your best bet is to use the stdint.h header. It defines typedefs that explicitly refer to the signedness and size of your variables. For example, a 16-bit unsigned integer is a uint16_t. It's part of the C99 standard, so it's available pretty much everywhere. See:

    http://en.wikipedia.org/wiki/Stdint.h

    0 讨论(0)
  • 2021-01-21 08:09

    Will you need values smaller than −32,768 or bigger than +32,767? If not, ignore the differnt sizes. If you do need them, there's stdint.h with fixed-size integers, singned und unsigned, called intN_t/uintN_t (N = number of bits). It's C99, but most compilers will support it. Note that using integers with a size bigger than the CPU's wordsize (16 bit in this case) will hurt performance, as there are no native instructions for handling them.

    0 讨论(0)
  • 2021-01-21 08:09

    avoid using the type int as it's size can depend upon architecture / compiler.

    use short and long instead

    0 讨论(0)
提交回复
热议问题