Hi,
I need to make sure my integer variable doesn't store more than 2 bytes. Usually i am writing programme on Linux machine where integer size is 4 byte.
Each byte can take the values 0 through 255 (=2^8-1). So, two bytes can take the values 255*255=65535, so would it be good to check integer range from 0-65535 to make sure it is having 2 byte value or is there any other standard way to achieve the same.

      if (a<0 || a>65535)
          {
          cout<<"validation failed";
           }

This could be where I'd use the sizeof() function instead. You may find int or integer could be 2 or 4 bytes today.

I need to make sure my integer variable doesn't store more than 2 bytes.

The integer will "store" however many bytes it is defined as having. See sizeof() as rproffitt says. No test is required to make sure that a 2-byte integer will store only two bytes, so the code you posted is unnecessary. There's nothing to "validate". If you're not using a very old compiler or computer or programming Microchips or something, integers will almost certainly be more than 16 bits.

Integers are signed, so a 16 bit integer would store 32,767 max. Your range would call for an UNSIGNED 16 bit integer.

I always like to use uint16_t as the type for this. Makes it obvious what the range is, including to the person reading the code. It's GUARANTEED to be 16 bits (of course it's NOT guaranteed that your compiler will support uint16_t). Include stdint.h as the header. If your compiler DOESN'T support uint16_t or you need 100% portable code, well, post again with why that won't work and we can cross that bridge. My hunch is that uint16_t will be fine.

http://en.cppreference.com/w/c/types/integer

Usually i am writing programme on Linux machine where integer size is 4 byte.

I saw this before but I guess it didn't really register in my head. I'm still not sure what problem you are facing, but it sounds like you already know you are using 4-byte/32-bit integers, so sizeof() is 4. If you are looking to change the type so that it will accomodate your range and only use two bytes, I would again advise going with uint16_t instead of int. As far as what bytes store what, keep in mind that if you are storing some number as a 4-byte 2's complement integer, the most significant bit will be the sign bit. That could be a factor or that could not be a factor, depending on what you are doing and why. With an UNSIGNED integer, there is no sign bit, bit manipulation/shifting can be easier and you have a bigger maximum value for cases like yours, where negative values are not allowed.

commented: That's the size of it. Clear as can be. +11

Thanks for your answers. I need to build same code on windows platform as well , so would it be possible to use uint16_t . Apart from this size of integer will be always 4 whether it stores 2 byte data or 4 byte data so i don't thing so it will be helpful in this case.

I need to build same code on windows platform as well , so would it be possible to use uint16_t

Hopefully this answer doesn't make you give up programming. Go with "yes" till you have problems. I'm a little out of my depth on portability questions so I offer no warranty on these comments, but see below.

Short answer is "yes". Slightly longer answer is "probably yes". Longer answer is "depends" and "try it". It depends on the compiler and the compiler flags and the operating system and the architecture and other stuff, but I tried it using g++ on both Windows and Linux and it worked in both places, so there you go. I would imagine it would work with most modern desktop compilers, but I don't know that for sure. Try it out.

#include <iostream>
#include <stdint.h>
int main()
{
    uint16_t number;
    std::cout << "# of bytes = " << sizeof(number) << std::endl; // output is 2
    return 0;
}

If you use the -std=c++11 g++ compiler flag, you can change the #include <stdint.h> line to #include <cstdint>. The benefit there is that cstdint is now part of the C++ standard (i.e. the recent C++ standard - C++11), which you should probably be compiling with unless there is a reason not to (that's my vote anyway). Visual Studio can be picky about files like stdint.h (i.e. might not have it), but since cstdint is now part of the C++11 standard, it should have that header. Again, it's all about which compiler you are using. Me, I like g++ for most stuff.

http://www.cplusplus.com/reference/cstdint/

Key line in link is here...

Optional: These typedefs are not defined if no types with such characteristics exist.*

I don't know if you are a student and just learning or if youn are a professional, but I remember when I was learning, I hated answers like I gave here (i.e. the "probably" and "should" qualifiers), but unfortunately it's one of the main challenges in coding. You figure out what you need as far as portability, try it out and often it works, but sometimes not, and then just make it work one way or another with #if tests or scotch-taping a custom .h file together or whatever it takes. Welcome to programming in the real world. There's also Boost.

http://www.boost.org/doc/libs/1_46_1/libs/integer/doc/html/boost_integer/cstdint.html

i believe unsigned short int is equalent to uint16_t and easily portable as well in all available platforms.

i believe unsigned short int is equalent to uint16_t and easily portable as well in all available platforms.

They are definitely not guaranteed to be equivalent, though they very often are equivalent. Here is my understanding. Again, could be wrong, but I don't think so and google seems to back this up. unsigned short will USUALLY be 16 bits on most systems, but there's no guarantee. uint16_t WILL DEFINITELY be 16 bits if uint16_t is defined. If an unsigned short or any other integral type is defined as 16 bits, then uint16_t will exist and will be exactly 16 bits. Thus if uint16_t IS NOT defined, then you cannot do what you are trying to do because unsigned short WILL NOT be 16 bits. Very often uint16_t is typedefed to be unsigned short. Again, that's my understanding and I'm not a compiler or C++ standard expert.

Then only guarantee you have is that uint16_t, if it is defined, will be exactly 16 bits. That I know. I THINK that if any 16-bit integral type is defined and stdint.h exists, then uint16_t will be defined. Perhaps someone who actually KNOWS will chime in. Sometimes you have to add a custom stdint.h file and maybe a quick configuration file and a few preprocessor directives to make things work if it's truly important. If uint16_t isn't defined, you might purposefully want to abort the compilation, so not compiling isn't necessarily a bad thing here.

But if you're going with regular old g++ on a regular Linux or Windows box, the odds are heavily in your favor that uint16_t is defined if things are installed right, so I think it's a fairly safe bet that everything will work out of the gate.

commented: +1 for the nod to uint16_t. +11

guys what do u suggest about unsigned short as it is also equilent to uint16_t (0-65535)as we don't have uint16_t convention in our code. Please suggest otherwise will go for below approach with simple integer.i beleive this way we can also validate if somebody is trying to store beyond 2 bytes .

  if (a<0 || a>65535)
      {
      cout<<"validation failed";
       }

Your code can fail. Why not use sizeof()? It's standard and while I can't guess why your setup doesn't have uint16_t and I can't find what compiler you are using (hint!) there is a standard way to check.

commented: One of these days I'll start making my posts as short and to the point as yours. +5

guys what do u suggest about unsigned short as it is also equilent to uint16_t (0-65535)

No, it's NOT equivalent. uint16_t is ALWAYS 16 bits. unsigned short is not always 16 bits. I mentioned that earlier. In put a bunch of qualifiers on the rest of my earlier post regarding my potential lack of knowledge, but not for this part. They are not guaranteed to be equivalent. It's wonderful that they happen to be the same on the two machines/compilers that you are using, as they are on mine, but there's no guarantee. Period. That's the last time I'll comment on that. I was going to capitalize that sentence for effect, but yelling is rude.

If uint16_t is not defined, you can always define/typedef it as an unsigned short. If stdint.h does not exist, you can add your own stdint.h and stick it at the end of your include path. If you know for sure that unsigned short is 16 bits and uint16_t isn't defined, it's really easy. typedef uint16_t to be unsigned short and use uint16_t in your code. That way anyone reading your code KNOWS FOR SURE that it is 16 bits.

As for complete portability and warnings to the user, that's why there are README files and comments in the code. You either write things so that portability is guaranteed by creating some configuration files that need to be run that check to make sure everything is in order and makes a change here and there or spits out a helpful error message if it isn't or you write a README and/or comment up the code explaining the limitations, assumptions, potential problems, or whatever it is that the user/professor needs to know in order to make your code work. Every project has assumptions, expectations, limitations, and explanations. If your target audience is computer/C++-literate, you just stick an error message and abort compilation telling me that uint16_t is not defined. From that, I can fix it. If your target audience is my mom, you had better make it so she just has to run a batch program that figures it all out. The README can be as short and sweet as "If you are AssertNull's mom and don't know what uint16_t is, this may or may not compile and run right. If it doesn't, call your son and make him fix it because I don't have time..." That's an acceptable README. I'm being a smart-aleck, but I'm also being serious.

You apparently have a situation where you don't have uint16_t doesn't exist and unsigned short is 16 bits. Your easiest solution is to fix it so your compiler has uint16_t defined as unsigned short from now on by adding it to your stdint.h file or creating a stdint.h if it doesn't exist. Voila. Problem solved. Next!

As for your test of a being in the range of 0 to 65535 and will it work, details, details, details. I don't know what your program does or what happens if that validation fails or whatever. You mention "storing" 16 bits. Again, if the unsigned short is 16 bits, that's how many bits will be "stored". If it is 32 bits, then it will "store" 32 bits. That's an entirely separate issue from validation. I'm guessing you are using the words "store" and "equivalent" more loosely than I am. I'm thinking we're talking right past each other. This will be my last post on this thread as I'm repeating myself from earlier posts. Good luck.

commented: Nice long explainer. Now we have the long and short of it. +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.