Saturday, May 22, 2010

About int <> char casting in c++?

I am attempting to create my own encryption algorithm. I basically would like the dycrpt/encrypt functions to accept a pointer and a byte amount and then modify that many bytes at the pointer. I understand what I want to do, but I am having problems working with the data. Is there any way to make a 1 byte integer? And would casting the pointer to that type, and then working with the data thru the new pointer work?





Also, for overflow, do I have to manually reset to 0 if it wud overflow, or can I rely on the fact that it will overflow as expected and not raise any exceptions?

About int %26lt;%26gt; char casting in c++?
The first answer is good. I just wanted to add that casting a pointer to a single byte and casting it back has potential for problems. Depending on the platform, a pointer is going to be 32 or 64 bits typically. Older systems used a segmented memory system that could use 16 bits. In either case, that data will not fit into a single byte. You should get compiler errors telling you about a potential loss of data.
Reply:1. char is already effectively a one byte integer. You may want to add "unsigned" to the front of it.





2. Not sure what the casting is buying you or what you are trying to do. If you want to access data through a pointer a byte at a time a char * (or unsigned char *) pointer is fine.





3. If Again, I'm not sure what it is that would overflow. If you want to make sure an integer doesn't overflow (and it's not meaningful to have values below 0), make it unsigned, it is guaranteed not to overflow, it will "roll back". For example the maximum unsigned int plus 2 would be equal to 1. In this example If you want it to be 0, not 1, then yes, you have to check for that yourself.

jasmine

No comments:

Post a Comment