Ultimos videos (En Youtube)
by mbrennan on Dic.31, 2009, under Noticias
MBF(Microsoft Binary Format) to IEEE convertion
by mbrennan on Jul.03, 2010, under Programacion/Coding/Sistemas Operativos
If you want to read this article in Spanish, then click here.
Google has it all, and if he doesn’t have it, probably doesn’t exists.
That’s what I encountered when I tried to solve this problem: Convert the MBF format to IEEE floating point standard.
When I was trying to found documentation about this issue, i found a lot of people asking the same question:
¿How I translate bits between these formats?
And the most of the cases, several failing algorithms were posted in the internet, guessing the convertion and especulating about
the format between these two types of floats.
¿Why do we need to know more about this deprecated Microsoft format? It’s an easy answer: because there is so much software that relies on the use of this floating point format to work and in my case, the QWK offline messages packet format use these floats to indexing messages. (Me, working in QWK is another story).
So, here I was, trying hardly to figure out how the fuck I convert these bits, and for the first place, I tried the scheme published in a old document of this QWK format in 1992.
QWK Mail Packet File Layout
by Patrick Y. Lee
[...]
Microsoft binary (by Jeffery Foy):
31 - 24 23 22 - 0 <-- bit position
+-----------------+----------+
| exponent | sign | mantissa |
+----------+------+----------+
IEEE (C/Pascal/etc.):
31 30 - 23 22 - 0 <-- bit position
+----------------------------+
| sign | exponent | mantissa |
+------+----------+----------+
[...]
So, I tried differents approach to convert these bytes, and I strongly refused to use C to solve this issue, because most of the work on QWK processing is in python, and bind a C function to python wasn’t my first option at all.
Desperately failing every time in this convertion, I managed to be very close to solve this scheme but, 4 bits were always wrong.
Researching even more in google, I found a concept in a snippet of code at markcoder site regarding to MBF –> IEEE convertion. A ‘Magic Number’.
I was like: Ok, that’s it. Fuck magic. There is no magic in computers. I refuse to believe in variables called ‘blackMagic’ or ‘magicMask’ or ‘fuckingMagicWhateverItThisShit’ (but, during the code of this function, i wrote several times this kind of vars during my trial and error period of coding).
So I remembered one sets of libraries called ‘Stamina’ for vb6 that mostly of the times, ages ago, i was using to do some dirty work in Visual Basic 6 and I found MBFIEE32.DLL with a function within: DxToIEEEs. My function. THE function.
And later, I was running this little program in VB6 in a virtualbox windows xp.
Ok. I got the correct numbers. The float rendered as an integer, just how I expected and the library was just doing what I needed.
So I started to dissasemble the segment of code that do the “black magic”.
After analysing the asm code, I finally wrote a working convertion in python.
I used BitString library to do the bit handling.
import struct
from bitstring import BitString
class Utils:
def StaminaMSBToIeeeDissasembled(self, pBytes):
""" This function was reverse engineered from MBF2IEE.DLL
from vb6 stamina libraries
CPU Disasm
-------------
MBFIEEE32 --> Function: DxToIEEEs (Stamina Lib for vb6)
-------------
Address Hex dump Command Comments
10001070 /$ 55 PUSH EBP ; C Convention
10001071 |. 8BEC MOV EBP,ESP
10001073 |. 56 PUSH ESI
10001074 |. 53 PUSH EBX ; End of C Convention
10001075 |. 8B75 08 MOV ESI,DWORD PTR SS:[ARG.1] ; We obtain the argument (my Single datatype)
10001078 |. 66:8B5E 02 MOV BX,WORD PTR DS:[ESI+2] ; and we get the second byte?
1000107C |. 66:8BCB MOV CX,BX ; we copy bx to cx, we'll need later
1000107F |. 66:33C0 XOR AX,AX ; clear ax
10001082 |. 8AC7 MOV AL,BH ; we copy the second byte to AL
10001084 |. 66:83F8 03 CMP AX,3 ; and we check if this byte is lower than 3
10001088 |. 72 1A JB SHORT ax_is_below_three
1000108A |. 2C 02 SUB AL,2 ; ok, it wasn't, so whe substract 2 to that byte
1000108C |. 86C4 XCHG AH,AL ; and whe save it to AH
1000108E |. 02DB ADD BL,BL ; we add ourselves o.o
10001090 |. 66:D1D8 RCR AX,1 ; rotate 1 bit to right
10001093 |. 66:83E1 7F AND CX,007F ; aha, i've seen this number before, we mask some bytes then
10001097 |. 66:0BC1 OR AX,CX
1000109A |> 66:8946 02 MOV WORD PTR DS:[ESI+2],AX ; yes, we save the result in these bytes.
1000109E |. 5B POP EBX ; and closing C convention, we fucking leave.
1000109F |. 5E POP ESI
100010A0 |. C9 LEAVE
100010A1 |. C2 0400 RETN 4
100010A4 |> 33C0 XOR EAX,EAX
100010A6 |. 8906 MOV DWORD PTR DS:[ESI],EAX
100010A8 \.^ EB F0 JMP SHORT 1000109A
We'll only care about two of them """
#print "Entering MSB ---> IEEE Long Int"
#pBytes = "\x00\xe0\x0f\x8b" # this number is equal to: 1151
ms = BitString(bytes=pBytes, length=32)
msle = ms[24:32] + ms[16:24] + ms[8:16] + ms[0:8]
a = ms[24:32]
b = ms[16:24]
cx = ms[16:24] + ms[24:32]
# we check that first unsigned byte is < 3 intA = int(struct.unpack('B', a.tobytes())[0]) if intA >= 3:
# we do a lot of things.
intA -= 2
a = BitString(uint=int(intA), length=8) # we save the changes to that byte
# now, we do secondByte*2
intB = int(struct.unpack('B', b.tobytes())[0])
intB *= 2
b = BitString(uint=int(intB), length=8) # we save the changes to that byte
# now comes a tricky part.
# in the dissasemble that i've done to the MBF2IEE.DLL (from stamina)
# here comes a rotate that needs 2 bytes to be done.
# so i'll create the final 2 bytes that will be stored in the final ieee convertion
convertionBytes = a + BitString(bytes="\x00", length=8)
convertionBytes = convertionBytes[15] + convertionBytes[0:15] # we rotate them to the right
# now, i need to mask the previously saved byte 'cx' with 0x7f
masked = struct.unpack('H', cx.tobytes())[0] & 0x007f
masked = BitString(uint=masked, length=16)
# and we OR convertionBytes with masked !
tmpResult = (convertionBytes | masked)
# we put things back together
ieee = tmpResult + ms[8:16] + ms[0:8]
i = struct.unpack('>f', ieee.tobytes())[0]
else:
# we do a lot of OTHER things
i = 0 # like return zero ;D
return int(i)
I really hope that this would be helpful to someone out there.
Conversion MBF(Microsoft Binary Format) a IEEE floating point
by mbrennan on Jul.03, 2010, under Programacion/Coding/Sistemas Operativos
Si queres leer este articulo en ingles, hace click aca.
Google lo tiene todo, y si no lo tiene, entonces no existe.
Eso fue lo que me encontre cuando quize resolver el siguiente problema: Convertir el viejo formato MBF al estandard IEEE.
Buscando documentacion sobre la conversion, me encontre con un monton de gente preguntando lo siguiente:
¿Como hago la conversión?
Y la mayor parte de los casos, habia algoritmos disponibles, sin documentar, prometiendo que funcionaban y no lo hacian, y largas
paginas especulando sobre como convertir entre estos formatos.
¿Porque necesitamos saber como funciona este viejo formato de punto flotante?
Facil: hay mucho software escrito, viejo, y a veces util, donde se utiliza. En mi caso particular, estoy trabajando sobre el viejo formato de mensajeria offline QWK, de los anaqueles de la historia pre-internet. Las queridas BBS. El porque trabajar sobre esto, es una larga historia a la cual no voy a entrar en detalles
Asi que aca estaba, tratando de entender como mierda convertir e stos bits, y como primer intento, use el esquema publicado en un viejo documento del formato QWK en 1992
QWK Mail Packet File Layout
by Patrick Y. Lee
[...]
Microsoft binary (by Jeffery Foy):
31 - 24 23 22 - 0 <-- bit position
+-----------------+----------+
| exponent | sign | mantissa |
+----------+------+----------+
IEEE (C/Pascal/etc.):
31 30 - 23 22 - 0 <-- bit position
+----------------------------+
| sign | exponent | mantissa |
+------+----------+----------+
[...]
Trate varias veces, sin exito, convertir estos bits y trate de no usar C para resolver este tema, porque gran parte de la aplicacion en la que estoy laburando esta hecha en python, y llamar funciones de C en python nunca fue mi primera opcion.
Fallando desesperadamente cada vez que intentaba convertir los floats, me di cuenta que habia 4 bits que mirase como se mirase, siempre estaban mal.
Buscando aun mas en google, encontre un concepto nuevo en la conversion en el sitio markcoder con respecto a la conversion MBF –> IEEE. “El numero magico”.
Y me dije: Al carajo, no hay magia en computación. Me niego fervientemente a creer en variables llamadas ‘magiaNegra’, ‘MascaraMagica’ o ‘putaMagiaEnEstaVariableCualquieraQueSeaPutoCaca’. (Aunque varias veces me sorprendi a mi mismo escribiendo variables magicas, en el duro proceso de prueba y error para corregir esos 4 bits del orto)
Entonces, la luz: Me acorde que hace muchisimos años, programando en Visual Basic 6, usaba una libreria: Stamina, para hacer mucho trabajo sucio que en vb6 era un toque mas complicado de organizar.
Encontre la lib MBFIEE32.DLL de Stamina, con una funcion adentro: DxToIEEEs. Mi funcion. LA funcion.
Minutos despues, estaba corriendo este pequeño programa en vb6 en una virtual box con windows xp.
Bien. Obtube los numeros esperados. Los Microsoft Floats me devolvian enteros, justo como esperaba.
Asi que asumi que la lib estaba haciendo exactamente lo que se le pedia. Convertir los putos numeros.
Entonces desensamble el pedazo de codigo que hacia la “magia negra”.
Despues de analisar el codigo en assembler, finalmente escribi un metodo funcionando en python.
Use BitString para la manipulacion de bits.
import struct
from bitstring import BitString
class Utils:
def StaminaMSBToIeeeDissasembled(self, pBytes):
""" This function was reverse engineered from MBF2IEE.DLL
from vb6 stamina libraries
CPU Disasm
-------------
MBFIEEE32 --> Function: DxToIEEEs (Stamina Lib for vb6)
-------------
Address Hex dump Command Comments
10001070 /$ 55 PUSH EBP ; C Convention
10001071 |. 8BEC MOV EBP,ESP
10001073 |. 56 PUSH ESI
10001074 |. 53 PUSH EBX ; End of C Convention
10001075 |. 8B75 08 MOV ESI,DWORD PTR SS:[ARG.1] ; We obtain the argument (my Single datatype)
10001078 |. 66:8B5E 02 MOV BX,WORD PTR DS:[ESI+2] ; and we get the second byte?
1000107C |. 66:8BCB MOV CX,BX ; we copy bx to cx, we'll need later
1000107F |. 66:33C0 XOR AX,AX ; clear ax
10001082 |. 8AC7 MOV AL,BH ; we copy the second byte to AL
10001084 |. 66:83F8 03 CMP AX,3 ; and we check if this byte is lower than 3
10001088 |. 72 1A JB SHORT ax_is_below_three
1000108A |. 2C 02 SUB AL,2 ; ok, it wasn't, so whe substract 2 to that byte
1000108C |. 86C4 XCHG AH,AL ; and whe save it to AH
1000108E |. 02DB ADD BL,BL ; we add ourselves o.o
10001090 |. 66:D1D8 RCR AX,1 ; rotate 1 bit to right
10001093 |. 66:83E1 7F AND CX,007F ; aha, i've seen this number before, we mask some bytes then
10001097 |. 66:0BC1 OR AX,CX
1000109A |> 66:8946 02 MOV WORD PTR DS:[ESI+2],AX ; yes, we save the result in these bytes.
1000109E |. 5B POP EBX ; and closing C convention, we fucking leave.
1000109F |. 5E POP ESI
100010A0 |. C9 LEAVE
100010A1 |. C2 0400 RETN 4
100010A4 |> 33C0 XOR EAX,EAX
100010A6 |. 8906 MOV DWORD PTR DS:[ESI],EAX
100010A8 \.^ EB F0 JMP SHORT 1000109A
We'll only care about two of them """
#print "Entering MSB ---> IEEE Long Int"
#pBytes = "\x00\xe0\x0f\x8b" # this number is equal to: 1151
ms = BitString(bytes=pBytes, length=32)
msle = ms[24:32] + ms[16:24] + ms[8:16] + ms[0:8]
a = ms[24:32]
b = ms[16:24]
cx = ms[16:24] + ms[24:32]
# we check that first unsigned byte is < 3 intA = int(struct.unpack('B', a.tobytes())[0]) if intA >= 3:
# we do a lot of things.
intA -= 2
a = BitString(uint=int(intA), length=8) # we save the changes to that byte
# now, we do secondByte*2
intB = int(struct.unpack('B', b.tobytes())[0])
intB *= 2
b = BitString(uint=int(intB), length=8) # we save the changes to that byte
# now comes a tricky part.
# in the dissasemble that i've done to the MBF2IEE.DLL (from stamina)
# here comes a rotate that needs 2 bytes to be done.
# so i'll create the final 2 bytes that will be stored in the final ieee convertion
convertionBytes = a + BitString(bytes="\x00", length=8)
convertionBytes = convertionBytes[15] + convertionBytes[0:15] # we rotate them to the right
# now, i need to mask the previously saved byte 'cx' with 0x7f
masked = struct.unpack('H', cx.tobytes())[0] & 0x007f
masked = BitString(uint=masked, length=16)
# and we OR convertionBytes with masked !
tmpResult = (convertionBytes | masked)
# we put things back together
ieee = tmpResult + ms[8:16] + ms[0:8]
i = struct.unpack('>f', ieee.tobytes())[0]
else:
# we do a lot of OTHER things
i = 0 # like return zero ;D
return int(i)
Realmente espero que esto le sirva a alguien.
Star Trek – Wesley & Picard
by mbrennan on Jun.15, 2010, under Artículos, Imagenes
Leave a Comment :picard, star trek, wesley crusher more...Duele.
by mbrennan on Jun.14, 2010, under Artículos, Mateo Brennan, Textos
Duele, porque estas ahí, sin que pueda tocarte.
Te miro desde lejos y se que lo estás.
Te miro desde cerca y se que lo estás.
¿Pero como estás tan distante
sin que mis brazos puedan envolverte
si es lo que queremos, che?
Porque claro, las obligaciones, el que hacer,
la absoluta y ominosa necesidad de ser
algo con el tiempo, pero sin acompañarlo.
Te sueño, bebiendo. Y fumando.
Y me masturbo recordando la ultima noche,
como un estúpido que no te poseyó nunca.
Colgandome del recuerdo, de lo que habrá pasado
en una cama helada por el invierno,
que nos calentó bajo una frazada,
y una bolsita de agua caliente.
Todavía está aquella mancha en la sábana,
húmeda de pasión que se niega a borrarse.
Y cada tanto, la huelo, y me da escalofrios.
No se si fue tuya o mia.
Y no me importa.
Es lo que tengo, y me aferro descaradamente
a ese accidente histórico, que solo yo recuerdo
porque jamás será escrito en ningun cuento
más que el mio.
Y me niego, te juro que me niego
a borrarlo.
Error en la migración de Ubuntu Karmic a Lucid Lynx “Fix symbol ‘grub_puts’ not found”
by mbrennan on Jun.06, 2010, under Programacion/Coding/Sistemas Operativos
Cada vez que el gestor de actualizaciones me avisa que hay una nueva version de ubuntu lista para instalarse en mi desktop, tiemblo.
No solo tiemblo porque esta es la 3era vez que tengo problemas al hacer el upgrade, si no que cada upgrade tiene problemas mas villeros.
En esta ocasion, mi pc despues del upgrade, no booteaba.
Apenas terminaba el POST, grub me decia:
Fix symbol 'grub_puts' not found
Entre el enojo y la falta de sorpresa ante un nuevo problema de actualizacion ubuntera, me propuse a recuperar mi maquina.
Primero, con un live cd viejo para reinstalar el grub. Y no tuve exito.
Despues, tratando de usar la linea de comandos:
grub rescue>
Tampoco tuve exito.
Hasta que me arme de valor y desempolve algunas cositas que habia olvidado con el paso del tiempo y las eras. Chroot era mi proxima opcion.
Booteando con el viejo live-cd (en este caso, un ubuntu 9.10), apenas tuve la posibilidad de levantar una terminal, tipie:
$ sudo -s
# fdisk -l
Fue sencillo encontrar la particion donde estaba instalada la actualizacion. Anteriormente, habia sido precavido y habia separado a /home de la particion donde esta el sistema operativo, asi, salvaguardar toda mi valiosa pornografia y algun que otro trabajo practico de la facultad.
Luego monté la particion root en /mnt
# mount /dev/sdXY /mnt
Y luego de haber montado mi root, decidi sabiamente, bindear /dev, /proc y /sys ya que habia leido en algunos antiguos manuscritos olvidados, que grub -y el mismisimo Perón- se valia de estos directorios para encontrar la felicidad y la buena fortuna.
# mount --bind /dev /mnt/dev
# mount --bind /proc /mnt/proc
# mount --bind /sys /mnt/sys
Habiendo dejado el terreno preparado, sumonnie al todo poderoso chroot para transformar mi entorno live-cd-esco a mi instalacion moribunda.
# chroot /mnt
Estando dentro ya de mi instalacion rotamente upgradeada, me puse a trabajar un poquito sobre grub para que haga las cosas como corresponde, y no como les pinto a la gente de Canonical.
# apt-get install grub-pc
# grub-install /dev/sdX
Un poco paranoico, por todo este asunto, hice un pasito de mas, para asegurarme que al menos hasta el proximo upgrade de ubuntu, mi maquina bootee sin verguenza.
update-grub
Despues de reiniciar. Fui feliz. Pude ver mi pornografia de nuevo.
Cinematronic – 404 – Rise
by mbrennan on Abr.19, 2010, under Videos
Tema: Rise de Cinematronic, del disco 404.
Video: Mateo Brennan
Pueden bajar este disco desde:
http://www.taringa.net/posts/musica/4672156/404—Mi-nuevo-disco-%282009%29-%28Homemade%29.html
getAdvice(“de la compañía.”);
by mbrennan on Abr.01, 2010, under Videos
Dos amigos incurren en una profunda disertación sobre las varias aristas que componen la circunstancia de la compañía.
Un cumpleaños con dresscode y regalo obligatorio
by mbrennan on Mar.19, 2010, under Artículos, Chats
[[ Para poner en tema: Invitación de cumpleaños, en un lugar paquetón de la capital. Aunque no suelo frecuentar ese tipo de sitios, no me parecia mal que mi amiga quiera festejarlo ahi. Hacia tiempo que no la veía y era una ocasión genial para ponerse al tanto de la vida del otro.
El día anterior a esta conversación, me había dicho despues de transmitirme la invitación que debía ir 'Bien vestido'. Conociéndola, me imaginé que la cita, a las cinco de la tarde de un sábado, debía ser con traje.
Bien vestido tambien puede suponer la forma en que me visto yo, cubriendo partes impúdicas, de manera cómoda, pero claramente no era el caso. Siendo que le tengo reticencia a ese tipo de vestimenta, para no decir que aborrezco vestirme así, le pregunté si era un dresscode del lugar, y que si era asi veía difícil mi asistencia, y pedí disculpas. Se desconectó antes de que le llegue mi mensaje, y hoy vuelve a hablarme. Aqui está la conversación, comentarios entre corchetes. ]]
[Censurado]
hola tosha
[El Chabon]
eaeaea
[Censurado]
y? vas a poder venir?
[El Chabon]
el lugar tiene dresscode ?
[Censurado]
eeeeeeeehh
si
[El Chabon]
m mm
vamos a ver q puedo hacer
[Censurado]
dale que te cuesta comprarte algo de ropa como la gente
[El Chabon]
me cuesta plata
toi viviendo solo
flaquita linda
[Censurado]
algo maso menos ponible
[El Chabon]
no se
veo
[Censurado]
ah mira que bien
si tenes
bueno no importa sino
venite como quieras
[El Chabon]
ahm, [entonces] no tiene dresscode
[Censurado]
no el dress code lo impuse yo
[El Chabon]
aha
porque?
[Censurado]
porque quiero una fiesta glamorosa
[El Chabon]
mmm
[Censurado]
bueno si no queres no vengass
Malo
(ofend)
[El Chabon]
mala vos, me conoces hace mas de 10 anyos, y sabes que me rompe soberanamente las pelotas que me digan como tengo que vestirme [ y seguis insistiendo con lo mismo! ]
[Censurado]
.jajaja
si
bueno
hacelo por mi
bueno
venite como quieras
pero me traes regalo
[El Chabon]
vos me estas jodiendo ? [te acabo de sugerir que al vivir solo, la plata no me sobra]
[Censurado]
no
te lo digo enserio
hace un esfuerzo
asi como yo hago el esfuerzo para invitarte a un lugar como la gente
[El Chabon]
acabas de cruzar una linea
metete a tu vida de carton de marca y a los lugares [y la ropa] como la gente bien en el orto
[Censurado]
ajajajjaja
ya sabia que te ibasa poner asi
queres venir o no?
[El Chabon]
[pfff, si ya sabias que me iba a poner asi, habiendo pasado esto mismo varias veces antes, porque insistis?]
ahora no infeliz
quien te crees que sos ?
que valgo yo, lo que tengo o lo que soy ?
pff
anda a cagar
Philamento [breakApart.com.ar + MateoBrennan]
by mbrennan on Mar.09, 2010, under Videos
breakApart + Mateo Brennan.
Musica: www.breakapart.com.ar
Philamento, sobre la verdad ultima.
Una serie de puntos considerados una verdad indiscutible, se pierden entre el sonido y la imagen, haciendo dificil la comprension del mensaje.
Finalmente, se dictamina la falacia en su ultimo punto, insultando sutilmente al espectador que intento interpretarlos.
getAdvice(“de los culos.”);
by mbrennan on Mar.04, 2010, under Videos
Un muchacho le pregunta a su amigo que hacer con respecto a un pedido de una mujer: Hacerle la cola. Luego de eso, discuten largamente sobre el tema tratando de definir si esta bien, o las ventajas y desventajas de romper un orto.






















