Squares

General FreeBASIC programming questions.
Locked
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Squares

Post by dodicat »

Hi Albert.
try this download.
I made a static lib from two base256 functions.
http://www.mediafire.com/file/clpqw6np3 ... ase256.zip
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

It errors over 7 places , the pack function is only good for 7 digit unpacks..

Dim As String text = "Hello Dave, How are you doing?" ' little endian
it unpacks fine i think , but pack only gets "Hello Da" plus a bunch of other chr's
it only packs the first 8 chr's

Code: Select all

'================================================================
' pack ascii numeric string to a straight binary number in a bigint
'================================================================
' the output bigint will have a length that is a multiple of 4 bytes
Function pack( Byref ascii As String) As String
    Dim As String a  ' a is the ascii input
    Dim As String b  ' b is the binary output
    Dim As Integer p, i, j, ch, blocks
    a = ascii
    '------------------------------------------------------------
    ' extract numerics from input string
    j = 0   '  in-place write pointer
    For i = 0 To Len(a) - 1
        ch = a[i]
        If (ch >= Asc("0")) And (ch <= Asc("9")) Then
            a[j] = ch
            j += 1
        Else
            Print "Invalid digit = "; Chr( ch ); ", in string at position ="; i
        End If
    Next i
    a = Left(a, j)  ' j is one ahead from string index = length of a
    '------------------------------------------------------------
    ' extend to next multiple of 9 digits
    i = Len(a)
    blocks = Int(0.99 + i / 9)  ' number of 9 digit blocks needed
    p = 9 * blocks
    a = String(p - i, "0") + a  ' pad to next multiple of 9 digits
    '------------------------------------------------------------
    ' decimal to binary conversion
    i = ( 8 + Len(a) * 3.32192809488) \ 8   ' bytes needed for binary
    blocks = 1 + (i \ 4)                    ' adjust to multiple of 4
    b = String(blocks * 4, Chr(0) ) ' binary destination string
    '------------------------------------------------------------
    Dim As Uinteger Ptr bp, bpz, bpcarry, bpdata
    bpz = Cast(Uinteger Ptr, Strptr(b)) ' binary output string[0]
    Dim As Ulongint product, carry, multiplier = 1e9
    bpdata = Cast(Uinteger Ptr, @product) ' bottom half of product
    bpcarry = bpdata + 1                ' top half of product
    '------------------------------------------------------------
    blocks = 1  ' blocks will be advanced as required by carry
    For i = 1 To Len(a)-8 Step 9   ' msd to lsd in blocks of 9
        bp = bpz    ' point back to the start
        carry = Valulng(Mid(a, i, 9))  ' take the next 9 digit block
        For j = 1 To blocks
            product = Clngint(*bp) * multiplier + carry
            *bp = Cuint(*bpdata)
            carry = Culngint(*bpcarry)
            bp += 1
        Next j
        ' advancing blocks only as needed doubles the speed of conversion
        If Carry Then
            *bp = carry
            blocks += 1 ' an exact count of the blocks used
        End If
    Next i
    b = Left(b, blocks * 4) ' keep only used blocks
    '-------------------------------------------------------------
    Return b
End Function

'-----------------------------------------------------------------------
' convert compressed binary string to ascii string
'-----------------------------------------------------------------------
' unpack a binary string to a decimal ascii string
Function unpack( Byref b As String ) As String
    Dim As String d = Chr( 0 )   ' initial decimal output string
    Dim As Integer i, j, product, carry
    '---------------------------------------------------
    ' change from base 256 to base 10
    For j = Len( b ) - 1 To 0 Step -1 ' bytes in base256 string, msb first
        carry = b[ j ]   ' byte to accumulate after multiply
        For i = Len( d ) - 1 To 0 Step -1   ' byte + ( decimal * 256 )
            product = 256 * d[ i ] + carry
            d[ i ] = product Mod 10
            carry = product \ 10
        Next i
        Do While carry > 0  ' output string typically overflows twice
            d = Chr( carry Mod 10 ) + d   ' extend output string
            carry = carry \ 10            '  as needed
        Loop
    Next j
    '---------------------------------------------------
    ' change from Ubyte to ASCII
    For i = 0 To Len( d ) - 1
        d[ i ] = d[ i ] + Asc( "0" )
    Next i
    Return d
End Function


'-----------------------------------------------------------------------
screen 12 ' " Linux Wine won't show a text console only graphics"

Dim As String text = "Hello Dave, How are you doing?"   ' little endian
Print text

dim as string text1 = unpack( text )
print text1

dim as string text2 = pack( text1 )
print text2

'-----------------------------------------------------------------------
Sleep
'-----------------------------------------------------------------------

Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

It works on my 32 bit Win7. Maybe your 64 bit system needs Integer changed to Long, as below.

Code: Select all

'================================================================
' pack ascii numeric string to a straight binary number in a bigint
'================================================================
' the output bigint will have a length that is a multiple of 4 bytes
Function pack( Byref ascii As String) As String
    Dim As String a  ' a is the ascii input
    Dim As String b  ' b is the binary output
    Dim As Long p, i, j, ch, blocks
    a = ascii
    '------------------------------------------------------------
    ' extract numerics from input string
    j = 0   '  in-place write pointer
    For i = 0 To Len(a) - 1
        ch = a[i]
        If (ch >= Asc("0")) And (ch <= Asc("9")) Then
            a[j] = ch
            j += 1
        Else
            Print "Invalid digit = "; Chr( ch ); ", in string at position ="; i
        End If
    Next i
    a = Left(a, j)  ' j is one ahead from string index = length of a
    '------------------------------------------------------------
    ' extend to next multiple of 9 digits
    i = Len(a)
    blocks = Int(0.99 + i / 9)  ' number of 9 digit blocks needed
    p = 9 * blocks
    a = String(p - i, "0") + a  ' pad to next multiple of 9 digits
    '------------------------------------------------------------
    ' decimal to binary conversion
    i = ( 8 + Len(a) * 3.32192809488) \ 8   ' bytes needed for binary
    blocks = 1 + (i \ 4)                    ' adjust to multiple of 4
    b = String(blocks * 4, Chr(0) ) ' binary destination string
    '------------------------------------------------------------
    Dim As ULong Ptr bp, bpz, bpcarry, bpdata
    bpz = Cast(ULong Ptr, Strptr(b)) ' binary output string[0]
    Dim As Ulongint product, carry, multiplier = 1e9
    bpdata = Cast(ULong Ptr, @product) ' bottom half of product
    bpcarry = bpdata + 1                ' top half of product
    '------------------------------------------------------------
    blocks = 1  ' blocks will be advanced as required by carry
    For i = 1 To Len(a)-8 Step 9   ' msd to lsd in blocks of 9
        bp = bpz    ' point back to the start
        carry = Valulng(Mid(a, i, 9))  ' take the next 9 digit block
        For j = 1 To blocks
            product = Clngint(*bp) * multiplier + carry
            *bp = Cuint(*bpdata)
            carry = Culngint(*bpcarry)
            bp += 1
        Next j
        ' advancing blocks only as needed doubles the speed of conversion
        If Carry Then
            *bp = carry
            blocks += 1 ' an exact count of the blocks used
        End If
    Next i
    b = Left(b, blocks * 4) ' keep only used blocks
    '-------------------------------------------------------------
    Return b
End Function

'-----------------------------------------------------------------------
' convert compressed binary string to ascii string
'-----------------------------------------------------------------------
' unpack a binary string to a decimal ascii string
Function unpack( Byref b As String ) As String
    Dim As String d = Chr( 0 )   ' initial decimal output string
    Dim As Long i, j, product, carry
    '---------------------------------------------------
    ' change from base 256 to base 10
    For j = Len( b ) - 1 To 0 Step -1 ' bytes in base256 string, msb first
        carry = b[ j ]   ' byte to accumulate after multiply
        For i = Len( d ) - 1 To 0 Step -1   ' byte + ( decimal * 256 )
            product = 256 * d[ i ] + carry
            d[ i ] = product Mod 10
            carry = product \ 10
        Next i
        Do While carry > 0  ' output string typically overflows twice
            d = Chr( carry Mod 10 ) + d   ' extend output string
            carry = carry \ 10            '  as needed
        Loop
    Next j
    '---------------------------------------------------
    ' change from Ubyte to ASCII
    For i = 0 To Len( d ) - 1
        d[ i ] = d[ i ] + Asc( "0" )
    Next i
    Return d
End Function


'-----------------------------------------------------------------------
screen 12 ' " Linux Wine won't show a text console only graphics"

Dim As String text = "Hello Dave, How are you doing?"   ' little endian
Print text

dim as string text1 = unpack( text )
print text1

dim as string text2 = pack( text1 )
print text2

'-----------------------------------------------------------------------
Sleep
'-----------------------------------------------------------------------

albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard , Your a God , it works just fine now.. Thanks for the code , It's for my newest data compressor idea i'm working on..
I'm using my averager code to compress data, don't know if it'll work or not , I'll play with it some and see.
They should promote you to "Code Ninja"

@Dodicat , I don't have GMP libs installed on my Linux system, not sure where the files would need to go , I'm somewhat new to Linux.
Richard's code is working now.
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

When i use unpack on raw file_data and step by values between 2 and 18.
It creates some strange numbers, some of them are prime, so they can only be divided by 1

I thought that i could break the unpack numbers , into co-numbers of equal length , can't do it.
None have an integer square root.

I thought i could half the unpack number, with sqr, but i cant happen....Got to rethink my plan..

I thought that maybe recording every other digit, i might be able to recreate the missing digits, but haven't yet figured out how to do it.

Any Ideas????
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

@ Albert.
The total bit or digit count in the factors of a number tends to be very similar to the bit or digit count in the original number.

Integer square roots become very rare as numbers get bigger and perfect squares get further apart.

Every bit of information is important if you want to regenerate the file or string from the BCD number.

There is a trap with this technique being used on raw file data. What happens when the most significant byte(s) of the string have a value of zero? The length of the string is then indeterminate. So you must define and append an end of string character that is not zero, say the ascii digit "0".
txt = txt + "0"
To fix the tail of the string, when you regenerate it, you can;
txt = Left( txt, InStrRev( ascii, "0" ) - 1 )
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

It is winter down here, so the nights are now long and dark, really good for reading about numbers.

This book, written in the 1960's, is well worth examination. Preview it as a 4.9 Mbyte pdf here.
http://www.plouffe.fr/simon/math/Albert ... umbers.pdf

A bargain, available at low cost new, or lower cost used. Find a copy with https://www.bookfinder.com

Chapter 21 is about factorisation. Page 239, is about Lehmer's Congruence Machine made from prime tooth gear wheels and used to factorise the big numbers of 1932.
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

!~~OFF TOPIC~~!

I re-wrote the rock band "The Who"'s song "Behind Blue Eyes" , i took out the blue eyes part cause i don't have blue eyes.
I made it into a story about a washed up boxer or wrestler, that's all depressed because he's not the king anymore.


( Genre = Rock )

( Title = No One Knows ) ( NOTE: my version of the Who's "Behind Blue Eyes" )

( entry music )

no one knows what it's like
to be be-rated
to be faded
quite the way i am

( short music )

no one knows what it's like
to be frustrated
to be obfuscated
it's all that i can stand

( music )

and my feel~~ings~~~~ they betray me
my feelings play me
world's smallest violin
and i've been hours
in depression
it ain't a cake walk
it's more than i can stand

( music )

no one knows what it's like
to be a bad man
to be a sad man
you know the way i am

( short music )

no one knows what it's like
to be a mad man
to be a had man
quite the way i am

( music )

and my feel~~ings~~~~ they betray me
my feelings play me
world's smallest violin
and i've been hours
in depression
it ain't a cake walk
it's more than i can stand

( music )

no one knows what it's like
to be defeated
to be unseated
it's all that i can stand

( short music )

no one knows what it's like
to be mistreated
to be depleted
i'm only just a man

( music )

and my feel~~ings~~~~ they betray me
my feelings play me
world's smallest violin
and i've been hours
in depression
it ain't a cake walk
it's more than i can stand

( short music )

and i've been hours
in depression
it ain't a cake walk
it's more than i can stand

( exit music )


albert_redditt@yahoo.com

Albert Redditt
315 W. Carrillo St. #104
Santa Barbara, Ca. 93101 U.S.A.



===========================================================
Here's me singing it:
http://www.mediafire.com/file/v5dp0jb4v ... nows-5.mp3
===========================================================
bfuller
Posts: 362
Joined: Jun 02, 2007 12:35
Location: Sydney, Australia

Re: Squares

Post by bfuller »

Hello Squares------its been a while since I lurked here. I bought a sailboat and it is much more fun than programming--but In still do make the occasional program for work-----mainly to set up a little test station to do electrical calibrations or testing.

Anyway, I just downloaded that book "Recreations in the Theory of Numbers" that Richard mentioned. Poor old ALBERT H. BEILER must have had a very poor social life !!!! LOL
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

bfuller wrote:I bought a sailboat and it is much more fun than programming …
Boat prices fell in Australia, starting a couple of years after the 2008 crash. It began in Sydney and spread outwards, finally reaching Tasmania a couple of years ago. I picked up a 38 ft steel ketch for my retirement. I'm now programming my integrated autopilot software, so I do know that my navigation computer runs FB.

Don't knock Beiler's approach. While the Fibonacci series is not part of number theory, the ratio of a beautiful woman's height to the height of her navel is phi = 1.618033, the golden ratio. I challenge you to repeat the experiment, do a survey. It can be very rewarding.
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Squares

Post by dodicat »

You guys down there, getting boats for your twilight years.

I've been watching the Americas cup on TV.
Science versus seamanship.

A 38 feet steel ketch is quite a beast.
Nevertheless, going out into the Southern Ocean on that would be challenging, FB or not.
Since I left the sea I haven't been back on a boat.
Not even a rowing boat.
I look landward for my twilight.
Boggy meadows, upland pastures, fallow fields ...
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

!!~~OFF TOPIC~~!!

I wrote a song about flipping boogers out the car window.


( Genre = Country )

( Title = Boog Air ) ( French for booger )


( entry music )

boog air , boog air
boog air on my fing air

boog air , boog air
boog air on my fing air

( music )

well i reach way up , into my nose
pull out a booger , long as a hose
i give it a fling , and off it goes
just where it'll land , nobody knows

i can't believe its , outta my nose
just give it a fling , the wind it blows
a passing car and , away it goes
stuck to the window , the booger knows

just pulled a booger , out of my nose
it's long and stringy , as booger goes
stuck to my finger , the booger flows
flung out the window , and off it goes

( music )

boog air , boog air
boog air on my fing air

boog air , boog air
boog air on my fing air

( music )

just pulled a booger , out of my nose
stuck to my finger , like goo it flows
i give it a fling , away it goes
just where it'll land , nobody knows

and a booger yes , a gooey mess
pulled out of my nose , a big ole mess
flung into the wind , and off it goes
sticking to a car , the booger shows

it was pretty big ,as boogers go
and from 1 to 10 , scored 8 or so
stuck to my finger , the booger flows
flung out the window , away it goes

( music )

boog air , boog air
boog air on my fing air

boog air , boog air
boog air on my fing air

( music )

boog air , boog air
boog air on my fing air

boog air , boog air
boog air on my fing air

( exit music )


albert_redditt@yahoo.com

Albert Redditt
315 W. Carrillo St. #104
Santa Barbara, Ca. 93101 U.S.A.
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

dodicat wrote:I look landward for my twilight.
Boggy meadows, upland pastures, fallow fields …
About 2700 years ago, the poet Homer, in The Odyssey, wrote how the ghost of Theban Teiresias, came to Ulysses in a dream and said “... you must take a well made oar and carry it on and on, till you come to a country where the people have never heard of the sea and do not even mix salt with their food, nor do they know anything about ships, and oars that are as the wings of a ship. I will give you this certain token which cannot escape your notice. A wayfarer will meet you and will say it must be a winnowing shovel that you have got upon your shoulder; on this you must fix the oar in the ground … ”.
This suggests that when you retire, you should travel to where your previous occupation is unknown, then you can tell your true stories to attentive listeners.
bfuller
Posts: 362
Joined: Jun 02, 2007 12:35
Location: Sydney, Australia

Re: Squares

Post by bfuller »

I have a Transworld 41----also a ketch, and also a beast--but an elegant beast-----certainly built for comfort, not speed. Perhaps we meet up one day----sailing to Tassie is on my list------when I retire it will be south for the summer and north for the winter. I doubt the "great southern ocean" will be on the list but we have already copped our fair share of the rough stuff during east coast lows!
Regarding electronics on board, I have a nice radar and plotter so interfacing to other data is an ambition. I have been studying NMEA2000 and its older cousin 0183 but the protocol is a bit daunting. I have a Raspberry Pi that should be able to do the job, perhaps in conjunction with an Arduino for the hard A/D. But time is my most scarce commodity, not ambition!
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Squares

Post by dodicat »

Many moons ago (1970's) I helped an acquaintance take a Wishbone ketch from Goole (English East coast near Hull) across the canals to The river Ribble (Near Preston, English west coast).
Then across the Irish sea to Strangford Lough (Northern Ireland).
Not a great feat of navigation, but the ketch was called Neptune's Daughter and originally belonged to Sir Alec Rose.
It had a standby engine which ran on TVO (tractor vaporising oil).
We unplugged the masts in Goole for the canal bit and re plugged them from a bridge on the Ribble.

That sums up my ketch experience, apart from dodging weekend sailors in and around various waterways.
Locked