Page 1 of 1

Operador Unary

PostPosted: Wed Dec 11, 2013 1:07 pm
by cnavarro
Hola
Existe el operador Unario (Unary, ~ operador) en Harbour?
O alguien lo tiene construido desde un valor decimal o hexadecimal?

Re: Operador Unary

PostPosted: Wed Dec 11, 2013 1:56 pm
by cnavarro
Bueno, a falta de pruebas exhaustivas creo que este código puede servir
Alguien que me lo pueda confirmar?

Code: Select all  Expand view

Function OperUnary( nNum )
Local nVal
Local cVal      := ""
Local nLen      := hb_BLen( DecToBin( nNum ) )
Local x
Local cNumBin   := DecToBin( nNum )

//  ? Valtype( DecToBin( 10 ) )

// ? HB_BITNOT( 5 ) // -6

For x = 1 to nLen
    if Substr( cNumBin, x , 1 ) = "1"
       cVal  := cVal + "0"
    else
       cVal  := cVal + "1"
    endif
Next x
nVal   := BinToDec( cVal )
//? cNumBin, nVal, cVal
Return nVal

 


Este link me ha sido de gran ayuda
http://harbouradvisor.blogspot.com.es/2 ... -bits.html

Re: Operador Unary

PostPosted: Fri Dec 13, 2013 9:47 am
by George
Cristobal,

Quizas esto te funcione:
Code: Select all  Expand view
#pragma BEGINDUMP
#include <hbapi.h>
#include <math.h>
HB_FUNC( C_COMPLEMENT )
{
    long long int nDecimal1;
    long long int nComplement;
    nDecimal1 = hb_parnll(1);
    nComplement = ~nDecimal1;
    hb_retnll( nComplement );
}
#pragma ENDDUMP
 

Solo tienes que llamar la funcion C_COMPLEMENT(nDecimal)
Donde nDecimal es el numero, en formato decimal, al cual quiere hallar el complemento.
Ejemplo C_COMPLEMENT(5000), devuelve -5001

Saludos,

George

Re: Operador Unary

PostPosted: Sun Dec 15, 2013 11:15 am
by cnavarro
George, gracias por tu interes
Eso mismo lo hace la función hb_bitNot
Code: Select all  Expand view

? hb_bitNot(5000)
 

Mi problema viene de convertir el -5001 a binario
Gracias de nuevo

Re: Operador Unary

PostPosted: Mon Dec 16, 2013 11:39 pm
by George
Cristobal,
Trata convirtiendo el valor decimal primero a Hexadecimal con la funcion de Harbour NumToHex(nDecimal), luego usa la funcion siguiente: HexToBinary(cHex)
Code: Select all  Expand view

FUNCTION HexToBinary(cHex)
    LOCAL nLenBin, nX, nPos, cBinNumber, cCharHex, cBinBase
    aHexBinary  := {    {"0",   "0000"},    {"1", "0001"}, {"2",    "0010"},  {"3""0011"}, {"4""0100"}, {"5", "0101"},;
                        {"6",   "0110"},    {"7",   "0111"},    {"8",   "1000"},  {"9""1001"},    {"A",   "1010"}, {"B", "1011"},;
                        {"C",   "1100"},        {"D", "1101"}{"E",   "1110"},  {"F""1111"}}

    cBinNumber := ""
    cHex := alltrim(cHex)

    FOR nX := len(cHex)  TO 1 STEP -1
         cCharHex := substr(cHex, -nX, 1)
         nPos := ascan(aHexBinary, { |a| a[1] == substr(cHex, -nX, 1)} )
         cBinBase := aHexBinary[nPos,2]
         cBinNumber := cBinNumber + cBinBase
    NEXT

RETURN (cBinNumber)


Saludos,

George,