Reputation: 491
Is it possible to store more than a byte value to a char type?
Say for example char c;
and I want to store 1000 in c
. is it possible to do that?
Upvotes: 1
Views: 9284
Reputation: 881463
Technically, no, you can't store more than a byte value to a char
type. In C, a char
and a byte are the same size, but not necessarily limited to 8 bits. Many standards bodies tend to use the term "octet" for an exactly-8-bit value.
If you look inside limits.h
(from memory), you'll see the CHAR_BIT
symbol (among others) telling you how many bits are actually used for a char
and, if this is large enough then, yes, it can store the value 1000.
Upvotes: 12
Reputation: 164
Char's width is system-dependent. But assuming you're using something reasonably C99-compatible, you should have access to a header stdint.h, which defines types of the formats intN_t and uintN_t where N=8,16,32,64. These are guaranteed to be at least N bits wide. So if you want to be certain to have a type with a certain amount of bits (regardless of system), those are the guys you want.
Example:
#include <stdint.h>
uint32_t foo; /* Unsigned, 32 bits */
int16_t bar; /* Signed, 16 bits */
Upvotes: 0
Reputation: 123468
The minimum size for a char
in C is 8 bits, which is not wide enough to hold more than 256 values. It may be wider in a particular implementation such as a word-addressable architecture, but you shouldn't rely on that.
Upvotes: 3
Reputation: 75906
The range of values you can store in a C type depends on its size, and that is not specified by C, it depends on the architecture. A char
type has a minimum of 8 bits. And typically (almost universally) that's also its maximum (you can check it in your limits.h
).
Hence, in a char you will be able to store from -128 to 127, or from 0 to 255 (signed or unsigned).
Upvotes: 5
Reputation: 27900
Probably not. The C standard requires that a char
can hold at least 8 bits, so you can't depend on being able to store a value longer than 8 bits in a char
portably.
(* In most commonly-used systems today, chars are 8 bits).
Upvotes: 1