+ 2
unsigned char in c/c++
is it common to use unsigned char to hold Integers from 0 to 255(to save memory) ?is it optimized? (I mean, doesn't converting it to a number(via (+) operator) slows down the program?)
10 ответов
+ 4
In most situations there isn't a significant gain or loss in performance or memory usage in either alternative because 100 million or billion elements would be needed before anyone notices on a modern laptop or desktop.
I tend to use unsigned char in c++ more to express to other developers that I know the range should stay pretty small. It is more to make the code and understood requirements more clear. It is rare to run out of processing time or RAM unless you're making a game, 3D renderer, or some other special software that pushes computing resources to the limit.
Even if char is roughly the same speed as int, is char any small amount faster or slower?
You'd have to test and benchmark this to be sure but I'll make some educated comments.
Reading and writing values with RAM may be slightly faster with char but not 32/8 times faster like you might think because RAM bus size transmits 64 bits and 72 bits at a time.
Extra CPU instructions may be needed to expand 8-bit to 16-bit or 32-bit sizes for some operations which may make unsigned char slower than int. These machine code instructions are some of the fastest operations, though. Assembly instructions like movsx(move sign extend) or movzx(move zero extend) are very close in speed to mov(move.. nothing extended because we're not changing size).
+ 2
thanks Martin Taylor and Josh Greig .
+ 2
Martin Taylor, who was assuming char was signed or unsigned? It looks like everyone here was saying unsigned char as if that was very explicit like you suggested.
You'd make a more important clarification to say that int isn't always 32-bit since that isn't standardized. I didn't mention that it wasn't standardized before because int is always bigger than char which is what his question is about.
+ 2
Martin Taylor int8_t bahaviors like signed char in some places like cin >>
and other implementations for char.
i think developers define it with this: typedef signed char int8_t
is my assume correct?
+ 2
Martin Taylor wrote, "Josh Greig it was Mehran Raeesi who stated "int8_t is equal with char and unit8_t with unsigned char" when char is not prefixed with signed or unsigned it cannot be assumed to be either."
Response:
ok. I see now. Cool.
Nice to see the int8_t and others in c++ 11. I didn't see those before in c++.
+ 1
Josh Greig In heavy 3D games, we need a lot of optimization, for example, for colors, it is better to use hex colors that use 8 bit. so an unsigned char is suitable for use, Do other developers do that?
+ 1
Martin Taylor int8_t is equal with char and unit8_t with unsigned char and so on.
int8_t v=97;
cout<<v;//result is a
what is the difference between these types and primitive types?