C how to add value to char and limit it so its will give only small letter ('z' + 2 = 'b')

huangapple go评论101阅读模式
英文:

C how to add value to char and limit it so its will give only small letter ('z' + 2 = 'b')

问题

I need to decode a string in c.
each char in the string I add him the value: 2^pos and then get the wanted letter.
but if I do 'z' + 2 its not going to give me a small letter. ( i will get a special char "|")

i thought about doing something like that:

(
value = 2^pos)

if (*(arr + k) >= 'a' && *(arr + k) <= 'z')
	{
		if (pos == 0)
		{
			value = 1;
		}
		if ('z' - (*(arr + k)) <= value)
		{
			*(arr + k) = 'a' + (value - ('z' - *(arr + k)));
		}
		else
		{ 
			*(arr + k) += value;
		}
		pos++;
	}

I also understand that there is a trick with %26 but i cant find the logic of it before doing it.

英文:

I need to decode a string in c.
each char in the string I add him the value: 2^pos and then get the wanted letter.
but if I do 'z' + 2 its not going to give me a small letter. ( i will get a special char "|")

i thought about doing something like that:

(
value = 2^pos)

if (*(arr + k) &gt;= &#39;a&#39; &amp;&amp; *(arr + k) &lt;= &#39;z&#39;)
	{
		if (pos == 0)
		{
			value = 1;
		}
		if (&#39;z&#39; - (*(arr + k)) &lt;= value)
		{
			*(arr + k) = &#39;a&#39; + (value - (&#39;z&#39; - *(arr + k)));
		}
		else
		{ 
			*(arr + k) += value;
		}
		pos++;
	}

I also understand that there is a trick with %26 but i cant find the logic of it before doing it.

答案1

得分: 1

a..=z有26个字符,所以你可以获取字符并减去'a'或'A'或其他。你可以使用该值找到模26,将该余数添加到'a'或'A'上将遵循循环。这是示例代码:

for (int j = 0; j <= 26+10; ++j) {
    printf("%c ", (j%26) + 'a');
}

或者

for (int j = 'a'; j <= 'z'+10; ++j) {
    printf("%c ", ((j-'a')%26) + 'a');
}
英文:

a..=z is 26 characters, so you can get the character and subtract it by 'a' or 'A' or whatever. You can use that value to find modulo 26 and upon adding that remainder to 'a' or 'A' will follow the cycle. Here's sample code:

for (int j = 0; j &lt;= 26+10; ++j) {
        printf(&quot;%c &quot;, (j%26) + &#39;a&#39;);
}

or

for (int j = &#39;a&#39;; j &lt;= &#39;z&#39;+10; ++j) {
        printf(&quot;%c &quot;, ((j-&#39;a&#39;)%26) + &#39;a&#39;);
}

huangapple
  • 本文由 发表于 2023年5月13日 16:37:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定