Funciones Sobre Potencia De 2: Bits Y And


Goto page 1, 2  Next

Subject: Funciones Sobre Potencia De 2: Bits Y And
¿Quien podría traducirme estas dos funciones hechas en javascript a Gambas3?
b2Math.b2NextPowerOfTwo = function(x)
{
x |= (x >> 1) & 0x7FFFFFFF;
x |= (x >> 2) & 0x3FFFFFFF;
x |= (x >> 4) & 0x0FFFFFFF;
x |= (x >> 8) & 0x00FFFFFF;
x |= (x >> 16)& 0x0000FFFF;
return x + 1;
};
b2Math.b2IsPowerOfTwo = function(x)
{
var result = x > 0 && (x & (x - 1)) == 0;
return result;
};

Last edited by jsbsan on Friday, 01 April 2016, 08:05; edited 2 times in total
Subject: Re: Funciones De Desplazamiento De Bits....
Hola, Jsban...

Yo por lo poco que he visto de Javascript hice una búsqueda de la función para ver en los otros lenguajes a los que ha sido portado B2box y si eso resultaba más esclarecedor... y me encontré con éste sitio:

http://aggregate.org/MAGIC/

El enlace

Allí entre tanta función aparece esto:

Citar:

Next Largest Power of 2

Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next largest power of 2. For a 32-bit value:

unsigned int
nlpo2(register unsigned int x)
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return(x+1);
}


Por lo que se puede entender que: Se trata de una función recursiva (y que utilizaria los pipe (" | ") para ello ) conocida como "Algoritmo de Precision SWAR" (o algo por el estilo)... lo que me llevó a esta pagina:

http://stackoverflow.com/questions/...algorithm-works

Espero te sirva.

Saludos.

Profile PM  
Subject: Re: Funciones De Desplazamiento De Bits....
Como bien sabes, gambas tiene una función para actuar el desplazamiento de los bits a derecha: Shr(). Pero prefiero usar una expresión explícita.

...de todas formas, teniendo tambien en cuenta lo que notó vicr, yo traduciría de javascript como sigue:
Private Function function_1(x As Integer) As Integer

x = x Or (x \ CInt(2 ^ 1)) And &7FFFFFFF&
x = x Or (x \ CInt(2 ^ 2)) And &3FFFFFFF&
etc...
etc....

Return x + 1

End


Private Function function_2(x As Integer) As Integer

Dim result As Integer

If (x > 0) And ((x And (x - 1)) = 0) Then result = 1

Return result

End
sttrah

Last edited by vuott on Thursday, 31 March 2016, 02:09; edited 6 times in total
Profile PM  
Subject: Re: Funciones De Desplazamiento De Bits....
Gracias Voutt y Vicr

Os dejo un ejemplo que he hecho con las funciones:

' gambas module file

Public Sub Main()

Dim n As Integer

For n = 2 To 100
Print "n:", n
Print "siguente potencia de 2:", b2NextPowerOfTwo(n)
'Print b2NextPowerOfTwo(n)
Print "<-->"
Print "¿es potencia de 2?:", b2IsPowerOfTwo(n)
'Print b2IsPowerOfTwo(n)
Print "---------------------------------------"
Next

End

Private Function b2NextPowerOfTwo(x As Integer) As Integer

x = x Or (x \ CInt(2 ^ 1)) And &7FFFFFFF&
x = x Or (x \ CInt(2 ^ 2)) And &3FFFFFFF&
x = x Or (x \ CInt(2 ^ 4)) And &0FFFFFFF&
x = x Or (x \ CInt(2 ^ 8)) And &00FFFFFF&
x = x Or (x \ CInt(2 ^ 16)) And &0000FFFF&
Return x + 1

End

Private Function b2IsPowerOfTwo(x As Integer) As Integer

If (x > 0) And ((x And (x - 1)) = 0) Then Return True
Return False

End


potencia2-0.0.1.tar.gz
Description: Funciones b2isPowerOfTwo y b2NexPowerOfTwo 
Download
Filename: potencia2-0.0.1.tar.gz
Filesize: 11.16 KB
Downloaded: 80 Time(s)
potencia2-0.0.1.tar.gz
Description: Funciones b2isPowerOfTwo y b2NexPowerOfTwo 
Download
Filename: potencia2-0.0.1.tar.gz
Filesize: 11.16 KB
Downloaded: 80 Time(s)
potencia2-0.0.1.tar.gz
Description: Funciones b2isPowerOfTwo y b2NexPowerOfTwo 
Download
Filename: potencia2-0.0.1.tar.gz
Filesize: 11.16 KB
Downloaded: 80 Time(s)

Subject: Re: Funciones De Desplazamiento De Bits....
jsbsan, porque no usas el tipo Boolean ?
Private Function b2IsPowerOfTwo(x As Integer) As Boolean

If (x > 0) And ((x And (x - 1)) = 0) Then Return True

End

Last edited by vuott on Thursday, 31 March 2016, 00:17; edited 1 time in total
Profile PM  
Subject: Re: Funciones De Desplazamiento De Bits....
Vuott:

Citar:
porque no usas el tipo Boolean ?

Me he equivocado, deberia haber puesto boolean.

Lo que no sabia, es que si una funcion no devuelve nada, devuelve 0 (false)

Saludos

Subject: Re: Funciones De Desplazamiento De Bits....
Julio:

¿ Y ese interés repentino por los bits ?.
¿ Quieres desplazarlos ?. ¿ Tienes bits ocupas ?.

Saludos

Subject: Re: Funciones De Desplazamiento De Bits....
Shell:
Citar:
¿ Y ese interés repentino por los bits ?

Estoy intentando empezar a traducir librerias de javascript, del tema del motor de fisica Bos2d, y me encontrado con varias funciones "raras" que no se muy bien para que se usan.

El caso es, que como en el sistema binario (0,1), es más fácil trabajar con potencias de 2 que con el sistema decimal, (y mucho más rápido para la máquina), aprovechamos "ese pequeño truco" para hacerlas en ese sistema. Creo que por eso se usan las funciones de desplazamiento: operaciones que en sistemas decimal consumen muchos ciclos de cálculo, en binario simplemente se trata de desplazar 0 y 1.

Saludos

Subject: Re: Funciones De Desplazamiento De Bits....
jsbsan escribió:  
Estoy intentando empezar a traducir librerias de javascript...

Shell,
yo y jsbsan hemos fundado la Schola traductionum de otros lenguajes a Gambas.

scuola_8

Profile PM  
Subject: Re: Funciones Sobre Potencia De 2: Bits Y And
Julio:

Debe ser complicado solo con unos y ceros.

Vuott:

Así que traductores. Que bien, entonces tambien traducirás personalmente de Python a gambas.
Claro que siempre habrá cosas que no se pueden traducir tan fácilmente. Debido a su complejidad o
lo que solicite.

¿ Se puede demostrar de alguna forma que hacer un calculo en binario es más rápido que en decimal ?.
¿ Nos valdría el perfilado ?. Se necesitaría hacer un buen número de operaciones.

Saludos

Last edited by Shell on Friday, 01 April 2016, 10:11; edited 1 time in total
Goto page 1, 2  Next

Page 1 of 2


  
You cannot post new topics
You cannot reply to topics
You cannot edit your posts
You cannot delete your posts
You cannot vote in polls
You cannot attach files
You can download files
You cannot post calendar events

   

This is a "Lo-Fi" version of our main content. To view the full version with more information, formatting and images, please click here.

Powered by Icy Phoenix based on phpBB
Design by DiDiDaDo

Generation Time: 0.1325s (PHP: -8% SQL: 108%)
SQL queries: 30 - Debug Off - GZIP Enabled