I am a little frustrated because all the books I have are working in integers or other that are at least four bytes each. I want to be able to read in a variable number of bytes in binary and alter them as I see fit then write them back.
How would I do this?
Thanks
I think chars is fastest (depending on what you are doing) because to play with binary you generally have to do some shifting around. If you're not doing any shifting and using bitwise ORs (|), bitwise ands (&) or bitwise XORs (^), then binary is probably easier/faster because there are fewer operations.
I think a 32 bit processor will generally read memory in 32 bit (4 byte) blocks anyways so if you are trying to save time by using chars, I don't think this will help.
If you are trying to save space, then just writing everything as chars when you save to a file. You don't need to cast then as ints. However, when you read the file, just ensure that you import them as single bytes.
If you wanted to read in a variable number of bytes you'd have to have some way of knowing how many bytes are in each word. I don't know if this method would work. you may get some compiling errors, but for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
unsignedlonglong input;
int numBytes; //You need to set this somehow
ifstream fin("myfile.txt")
fin >> input;
switch numBytes
{
case 1:
cout << (unsignedchar)(input & 0xff);
case 2:
cout << (unsignedshort)(input & 0xffff);
case 4:
cout << (unsignedint)(input & 0xffffffff);
case 8:
cout << (unsignedlonglong)(input & 0xffffffffffffffff);
}
If you really just don't want to use more than 1 byte, then simply don't use anything but chars or bools in your code.