Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re: Add 1 to an arbitrary-length binary string

by BillKSmith (Monsignor)
on Nov 16, 2023 at 20:43 UTC ( [id://11155662] : note . print w/replies, xml ) Need Help??

in reply to Add 1 to an arbitrary-length binary string

It seems that you are trying to make a minimal range by setting the range end to one bit higher than the range start. Incrementing the last character is easy.
use strict; use warnings; my $str = 'arbitrary length'; substr($str, -1, 1) = chr(ord(substr($str, -1, 1))+1); print $str;
This increments the Unicode code-point rather than its utf8 encoding that your integer arithmetic would increment. In the cases where it makes a difference, I suspect that this is what the author of your document had in mind. This will fail if your strings are restricted to ASCII Characters and the last character of the string is an ASCII DEL (U+7F).