First of all, im new to coding and I thought sometime about the problem and I tried to google it. I already have a workaround I just want to know if it is possible in another way. Im taking the cs50 course and I should write an encryption function.
My problem is, that my char gets temporarily bigger then 127 and then gets truncated. So is it nevertheless possible to calculate with a certain char temporarily before I save it it into a memory address and truncate it?
The part where I think the problem should be:
for
(int i = 0; i < strlen(ui); i++)
{
if
(isupper(ui[i]))
{
ui[i] += key;
if
(ui[i] > 90)
{
ui[i] -= 26;
}
}
if
(islower(ui[i]))
{
ui[i] += key;
if
(ui[i] > 122)
{
ui[i] -= 26;
}
}
and it gets truncated e.g. if the key gets bigger then 6 for an input of z.
So can I write it somehow, that the 26 gets subtracted before it gets into storage or is (what I think atm) not possible because as soon as it gets bigger then 127 even if it is in one line, it gets truncated?
Workaround ( I thought about writing now): I will subtract 96 before so I get calculate with numbers between 1 and 27 and add it after.
thank you for advice in advance.
My problem is, that my char gets temporarily bigger then 127 and then gets truncated. So is it nevertheless possible to calculate with a certain char temporarily before I save it it into a memory address and truncate it?
Yes, it is possible, and you do not have to do anything special to achieve it. In a C expression, all arithmetic operands of integer types narrower than int
are converted to int
or wider, and the computation is performed in that wider type, producing a result of that type. It is then narrowed again if necessary for assignment to an object of narrower type.
Note, however, that
A narrowing conversion to a signed integer type has implementation-defined behavior if the initial value cannot be represented in the target type. That can include raising an implementation-defined signal. It is not safe to assume that the most-significant bytes will just be chopped off when they contain values other than zero.
What you describe is not what the code presented actually does. In particular, I take you to be talking about this:
ui[i] += key;
It is not a problem to compute ui[i] + key
in this case, but there is no particular delay there before writing the result to memory. That's what the assignment part of +=
does.
You would be better off avoiding the situation altogether. For instance,
if (islower((unsigned char) ui[i])) {
ui[i] = (((ui[i] - 'a') + key) % 26) + 'a';
}
Do also note, however, that that (and your original) assumes that the numeric values of the lower-case letters for a contiguous block. That is frequently true, but not universally so.