Seu shell pode manipular ops bit a bit, no entanto, para qualquer processamento sério, ele será terrivelmente lento e não poderá manipular nada mais do que 20 ou mais dígitos de cada vez. Ainda:
sh <<\CMD
printf 'printf "%%b" "\0$((%04o^04))"' "'a" |\
. /dev/stdin
CMD
#OUTPUT
A
Eu usei bc
no passado para pegar bytes em binário, então sua pergunta me levou a pesquisar ...
Exclusive-or (XOR) para o GNU bc
If you've found your way across the internet to this question, chances are you're looking for bc's equivalent of C's
^
operator.Disturbing fact: no such thing exists in
bc
. Inbc
, the up-arrow operator is used for integer exponentiation, that is,2^x
returns a power of 2 and not x with bit 2 flipped. If you're looking for equivalents to the bitwise operators for XOR as well as AND, OR and a few more exotic relatives, check out this site's logic.bc, and its relatives which contain functions to perform each of these.If you're looking for a logical
XOR
to put in an if statement, like logical&&
and||
, try using!=
and surrounding your conditions with brackets. e.g.:
c=0;if((a==1)!=(b==2)){c=3}
Will set c to 3, if a is 1 or b is 2, but not if a is 1 and b is 2 at the same time
(Once upon a time, this was the secret to the internals of the logic.bc xor() function, but this has been superseded by a faster algorithm.)
O texto acima é da bc
FAQ. A função logic.bc
mencionada acima inclui a lógica bitwise
que você está procurando. Pode ser encontrado aqui . Sua descrição:
A large suite of functions to perform bitwise functions such as AND, OR, NOT and XOR. Uses twos complement for negative numbers, unlike previous versions of this file, which had no support at all. Some of the functions here will use the global bitwidth variable, which itself is initialised as part of this file, to emulate byte/word sizes found in most computers. If this variable is set to zero, an infinite bitwidth is assumed. Many functions will display a warning if there is suspicion that a secondary floating point representation of a number has been generated, e.g.:
1.1111... is an SFPR of
10.0000...;'These warnings can be disabled by setting the global variable
sfpr_warn
to0
(default is 1).
- Tamanho de palavras fixas
- Tamanho infinito de palavras
- Comum bit a bit
- Dois complementos
- Mudança de bit
- código cinza
- 'Multiplicação'
- Ponto flutuante
- Ponto flutuante 'Multiplicação'
- Código cinza + ponto flutuante