Sunday 15 October 2017

Konverter The Nummer 244 Til Binære Alternativer


binær - Sett inn og trekk ut felt fra binære strenger. Denne kommandoen gir muligheter for å manipulere binære data Underkommandobinformatet skaper en binær streng fra normale Tcl-verdier. For eksempel, gitt verdiene 16 og 22, på en 32-biters arkitektur, kan det produsere en binær streng med 8 byte som består av to 4-byte-tall, en for hver av tallene. Den binære skanneren underkommandoer trekker det motsatte ut data fra en binær streng og returnerer den som vanlige Tcl-strengverdier. Den binære kode og binære dekoder-subkommandoer konverterer binære data til eller fra strengkodninger, for eksempel base64 som brukes i MIME-meldinger, for eksempel. Når du koder binær data som en lesbar streng, sendes de binære dataene til den binære kodekommandoen sammen med navnet på kodingen som skal brukes og hvilken som helst koding - specifikke ønskede alternativer Data som er kodet kan konverteres tilbake til binær form ved hjelp av binær dekoder Følgende formater og alternativer støttes. base64 Basen64 binær enco ding brukes ofte i postmeldinger og XML-dokumenter, og bruker for det meste store og små bokstaver og siffer. Det har forskjellen på å kunne omskoles vinsjelt uten å miste informasjon. Ved koding støttes følgende alternativer.-maxlengde Indikerer at utdataene skal deles i linjer med ikke lengre tegn. Som standard er linjene ikke delt - wrapchar-tegn. Indikerer at når linjer deles på grunn av - maxlen-alternativet, skal tegn brukes til å skille linjer. Som standard er dette en newline karakter, n. During dekoding, er følgende alternativer støttet. - strenge Instruerer dekoderen for å kaste en feil hvis den møter hvite mellomrom. Ellers ignorerer de dem hex. Heks binære koding konverterer hver byte til et par heksadesimale siffer i big-endian form. Ingen alternativer støttes under koding Under dekoding blir følgende alternativer støttet. - streng Instruerer dekoderen for å kaste en feil hvis den møter hvitt plass tegn Ellers ignorerer de dem uuencode Binærkodingen uuencode pleide å være vanlig for overføring av data mellom Unix-systemer og på USENET, men er mindre vanlig i disse dager, etter å ha blitt i stor grad erstattet av base64 binær koding. Ved koding blir følgende alternativer støttet .-makslengden Angir at utgangen skal deles i linjer med ikke lengre tegn. Som standard deles linjene ikke - wrapchar-tegn. Indikerer at når linjer deles på grunn av - maxlen-alternativet, skal tegn brukes til å skille linjer Som standard er dette en newline-karakter, n. During dekoding støttes følgende alternativer. - strenge Instruerer dekoderen for å kaste en feil hvis den møter hvite plasskarakterer. Ellers ignorerer de dem. Kommandoen binærformat genererer en binær streng hvis layout er spesifisert av formatString og hvis innhold kommer fra de ekstra argumenter Den resulterende binære verdien returneres. FormatString består av en sekvens av null eller flere feltpecifikasjoner separert med null eller flere mellomrom Hvert feltspesifikator er en enkelt type karakter etterfulgt av et valgfritt flagg karakter etterfulgt av en valgfri numerisk telling De fleste feltspesifikatorer bruker et argument for å oppnå verdien som skal formateres Typetegn angir hvordan verdien skal formateres Tellingen angir vanligvis hvor mange elementer av den angitte typen som er tatt fra verdien Hvis den er til stede, er tellingen et ikke-negativt desimaltal eller som vanligvis indikerer at alle elementene i verdien skal brukes Hvis antall argumenter ikke samsvarer med antall felt i formatstrengen som forbruker argumenter, genereres en feil. Flaggkarakteren ignoreres for binærformat. Her er et lite eksempel for å klargjøre forholdet mellom feltangivelsene og argumentene. Det første argumentet er en liste over fire tall, men på grunn av tellingen av 3 for tilhørende felt spesifiserer, vil bare de tre første bli brukt. Det andre argumentet nt er knyttet til den andre feltspecifikatoren. Den resulterende binære strengen inneholder de fire tallene 1 0, 2 0, 3 0 og 0 1. Hver type tellerpar beveger en imaginær markør gjennom binærdata, lagrer byte ved gjeldende posisjon og fremover markøren til like etter siste byte lagret Markøren er i utgangspunktet på posisjon 0 ved begynnelsen av dataene. Typen kan være en av de følgende tegnene. a Lagrer en byte streng med lengde telling i utgangsstrengen Hver tegn er tatt som modulo 256 dvs. den lave byte av hvert tegn brukes, og den høybyte kasseres, så når lagring av tegnstrenger ikke helt uttrykkbar ved hjelp av tegnene u0000-u00ff, skal konverteringskoden for koding brukes først for å endre strengen til en ekstern representasjon dersom dette trunkering er ikke ønsket, dvs. hvis tegnene ikke er en del av ISO 8859-1 tegnsettet. Hvis arg har færre enn tellebyte, brukes ytterligere nullbyte til å kaste ut feltet. Hvis arg er lengre enn th e angitt lengde, vil de ekstra tegnene bli ignorert Hvis telle er så blir alle bytes i arg formatert. Hvis teller er utelatt, vil et tegn bli formatert. For eksempel. vil du returnere en streng tilsvarende alfa 000 000bravoc. will returnere en streng tilsvarende 342 202 254 som er UTF-8 byte-sekvensen for en Euro-valuta karakter og. Vil returnere en streng tilsvarende 244 som er ISO 8859-15 byte-sekvensen for en Euro-valuta karakter. Kontrast disse to siste med. som returnerer en streng tilsvarende 254 dvs. xac ved å avkorte høybiter av tegnet, og det er sannsynligvis ikke det som er ønsket. Dette skjemaet er det samme som unntatt at mellomrom brukes til polstring i stedet for nuller For eksempel. vil returnere alpha bravoc. b Lagre en streng av binære tall i lav til høy rekkefølge innen hver byte i utgangstrengen Arg må inneholde en sekvens på 1 og 0 tegn. De resulterende bytene sendes i første til siste rekkefølge med biter som er formatert i low-to-hig h-ordre i hver byte Hvis arg har færre enn telle siffer, vil nuller bli brukt for de resterende brikkene Hvis arg har mer enn det angitte antall siffer, vil de ekstra sifferene bli ignorert. Hvis telle er så vil alle sifferene i arg formatert Hvis teller er utelatt, vil et siffer bli formatert Hvis antall bitformatert ikke slutter ved en bytegrense, vil de resterende bitene av den siste byten være nuller For eksempel. vil du returnere en streng tilsvarende x07 x87 x05. B Dette skjemaet er det samme som b bortsett fra at bitene lagres i høy til lav rekkefølge innen hver byte. For eksempel. vil du returnere en streng tilsvarende xe0 xe1 xa0.H Lagrer en streng av telle heksadesimale sifre i høy-til - lav innenfor hver byte i utgangstrengen Arg må inneholde en sekvens av tegn i settet 0123456789abcdefABCDEF De resulterende bytene sendes i første til siste rekkefølge med heksesifrene formateres i høy til lav rekkefølge innen hver byte Hvis arg har færre enn telle sifre, så nuller vil være deg sed for de resterende tallene Hvis arg har mer enn det angitte antall sifre, vil de ekstra sifferene bli ignorert. Hvis tallet er, vil alle sifferene i arg bli formatert. Hvis teller er utelatt, vil ett siffer bli formatert. Hvis tallet sifre formatert slutter ikke ved en byte grense, de resterende biter av den siste byten vil være nuller For eksempel. vil du returnere en streng tilsvarende xab x00 xde xf0 x98.h Dette skjemaet er det samme som H bortsett fra at sifrene er lagret i lav til høy rekkefølge innen hver byte Dette er sjelden nødvendig For eksempel. vil du returnere en streng som tilsvarer xba x00 xed x0f x89.c Lagrer ett eller flere 8-biters heltallverdier i utgangstrengen Hvis ingen teller er spesifisert, så arg må bestå av en heltallverdi Hvis teller er spesifisert, må arg bestå av en liste som inneholder minst så mange heltall. De 8 ordene med lav rekkefølge av hvert heltall lagres som en byteverdi ved markørposisjonen. Hvis telle er så alle heltallene i listen er formatert hvis antall elem ents i listen er større enn å telle da de ekstra elementene blir ignorert. For eksempel. vil du returnere en streng tilsvarende x03 xfd x80 x04 x02 x05 while. will generere en feil. s Dette skjemaet er det samme som c bortsett fra at det lagrer en eller flere 16-biters heltall i liten endian byte rekkefølge i utgangsstrengen 16-biters lav-ordre av hvert heltall lagres som en tobyteverdi ved markørposisjonen med minst signifikante byte lagret først For eksempel. vil du returnere en streng tilsvarende x03 x00 xfd xff x02 x01.S Dette skjemaet er det samme som s, bortsett fra at det lagrer ett eller flere 16-biters heltall i storendisk byte rekkefølge i utdatastrengen For eksempel. vil du returnere en streng tilsvarende x00 x03 xff xfd x01 x02.t Dette skjemaet mnemonisk liten er det samme som s og S, bortsett fra at det lagrer 16-biters heltall i utgangsstrengen i den native byte rekkefølgen av maskinen der Tcl-skriptet kjører. For å bestemme hva den native byte rekkefølge av maskinen er, referer til byteOrder-elementet i tclpla tform array i Dette skjemaet er det samme som c bortsett fra at det lagrer ett eller flere 32-biters heltall i liten endian byte rekkefølge i utgangsstrengen. De 32 bitene av lavt rekkefølge av hvert heltall lagres som en firebyteverdi ved markørposisjonen med minst signifikante byte lagret først For eksempel. vil du returnere en streng tilsvarende x03 x00 x00 x00 xfd xff xff xff x00 x00 x01 x00.I Dette skjemaet er det samme som jeg unntatt at det lagrer en eller flere en eller flere 32-biters heltall i storendisk byte rekkefølge i utgangsstrengen For eksempel. vil du returnere en streng tilsvarende x00 x00 x00 x03 xff xff xff xfd x00 x01 x00 x00.n Dette skjemaet mnemonisk tall eller normalt er det samme som jeg og jeg bortsett fra at det lagrer 32-biters heltall i utgangsstrengen i den native byte rekkefølge av maskinen der Tcl-skriptet kjører. For å bestemme hva den innfødte byteordningen til maskinen er, referer til byteOrder-elementet i tclplatform arrayet w Dette skjemaet er det samme som c bortsett fra at det lagrer ett eller flere 64-biters heltall i n liten endian byte rekkefølge i utgangsstrengen 64-bitene av hvert heltall lagres som en åtte-byteverdi ved markørposisjonen med minst signifikante byte lagret først For eksempel. vil du returnere strengen HelloTcl. W Dette skjemaet er det samme som w bortsett fra at det lagrer ett eller flere ett eller flere 64-biters heltall i storendisk byte rekkefølge i utgangstrengen For eksempel. vil du returnere strengen BigEndian. m Dette skjemaet er mnemonisk speilet til w det samme som w og w bortsett fra at det lagrer 64-biters heltall i utgangsstrengen i den innfødte byte rekkefølge av maskinen der Tcl-skriptet kjører. For å bestemme hva den innfødte byteordningen til maskinen er, referer til byteOrder-elementet i tclplatform array f Dette skjemaet er det samme som c bortsett fra at det lagrer ett eller flere én eller flere enkeltspennende flytpunktspunkter i maskinens innfødte representasjon i utgangsstrengen. Denne representasjonen er ikke bærbar på tvers av arkitekturer, slik at den ikke skal brukes å kommunisere flytpunktsverdier over hele nettverket Størrelsen på et flytpunktspunkt kan variere på tvers av arkitekturer, slik at antall byte som genereres kan variere Hvis verdien overskrider maskinens native representasjon, vil verdien av FLTMAX som definert av systemet være brukt i stedet Fordi Tcl bruker tosidige flytpunktspunkter internt, kan det være noe tap av presisjon i konvertering til enkelthet. For eksempel på et Windows-system som kjører på en Intel Pentium-prosessor. vil returnere en streng tilsvarende xcd xcc xcc x3f x9a x99 x59 x40.r Dette skjemaet mnemonisk reelt er det samme som f, bortsett fra at det lagrer enkelt-presisjon flytpunktnumrene i liten endian rekkefølge Denne konverteringen gir bare meningsfull produksjon når den brukes på maskiner som bruker IEEE-flytpunktspresentasjonen veldig vanlig, men ikke universell R Dette skjemaet er det samme som r bortsett fra at det lagrer enkelt-presisjon flytpunktnumrene i storendian rekkefølge d Dette skjemaet er det samme som f bortsett fra at det lagrer ett eller flere ett eller flere dobbelt-presisjons flytpunktsnummer i maskinens native representasjon i utgangsstrengen. For eksempel på et Windows-system som kjører på en Intel Pentium-prosessor. vil returnere en streng tilsvarende x9a x99 x99 x99 x99 x99 xf9 x3f. q Dette skjemaet er mnemonisk speilet til d er det samme som d, bortsett fra at det lagrer dobbeltdefinisjonen flytende punktnumre i liten endian rekkefølge Denne konverteringen gir bare meningsfull produksjon når den brukes på maskiner som bruker IEEE-flytende poengrepresentasjon veldig vanlig, men ikke universell Q Dette skjemaet er det samme som q, bortsett fra at det lagrer de dobbelte presisjon flytpunktstallene i bigendian rekkefølge x Butikker teller nullbyte i utgangsstrengen Hvis teller ikke er spesifisert, lagrer en null byte Hvis telle genererer en feil Denne typen forbruker ikke et argument For eksempel. vil du returnere en streng tilsvarende abc 000def 000 000ghi. X Flytter markøren tilbake teller byte i utdatastrengen Hvis jeg teller jeg s eller er større enn den nåværende markørposisjonen, så er markøren plassert på posisjon 0 slik at neste lagrede byte blir den første byten i resultatstrengen. Hvis teller utelates, flyttes markøren tilbake en byte. Denne typen forbruker ikke et argument For eksempel. vil du returnere dghi. Flytter markøren til det absolutte stedet i utgangsstrengen som er spesifisert ved teller Posisjon 0 refererer til den første byten i utgangsstrengen Hvis teller refererer til en posisjon utenfor den siste byte som er lagret så langt, vil nullbyte bli plassert i de uinitierte posisjonene og markøren vil bli plassert på den angitte plasseringen Hvis teller er så flyttes markøren til den nåværende enden av utdatastrengen Hvis teller utelates, vil en feil bli generert Denne typen forbruker ikke et argument For eksempel vil du returnere abfdeghi 000 000j. Den binære skanningskommandoen analyserer felt fra en binær streng, og returnerer antall konverteringer som utføres String gir inndatabyteene som skal analyseres en byte per tegn, og tegn som ikke kan representeres som en byte, har høye biter hakket og formatString indikerer hvordan man analyserer det Hver varnavn gir navnet til en variabel når et felt blir skannet fra streng resultatet blir tilordnet til den tilsvarende variabelen. Som med binært format består formatString av en sekvens av null eller flere feltpecifikasjoner separert med null eller flere mellomrom. Hver feltpecifikator er et enkelt tegn, etterfulgt av et valgfritt flagg karakter etterfulgt av en valgfri numerisk telling. De fleste feltpecifikatorer bruker et argument for å oppnå variabelen som de skannede verdiene skal plasseres Typetegn angir hvordan binære data skal tolkes Tellingen angir vanligvis hvor mange elementer av den angitte typen som er tatt fra dataene Hvis det er til stede, er tellingen et ikke-negativt desimaltal eller som vanligvis indikerer at alt De gjenværende elementene i dataene skal brukes Hvis det ikke er nok byte igjen etter at nåværende markørposisjon skal tilfredsstille gjeldende feltspecifikator, blir den tilsvarende variabelen uberørt og binær skanning returneres umiddelbart med antall variabler som ble satt hvis Det er ikke nok argumenter for alle feltene i formatstrengen som forbruker argumenter, da oppstår en feil Flagg cha racter kan du få til å få noen typer til å bli lest som usignerte verdier Flagget er akseptert for alle felttyper, men ignoreres for ikke-heltallfelt. Et lignende eksempel som med binært format bør forklare forholdet mellom feltangivelser og argumenter i tilfelle av binær skanning subkommandoen. Denne kommandoen gitt den binære strengen i variabelen er lang nok tilordner en liste over tre heltall til variabelen først og tilordner en enkelt verdi til variabelen andre Hvis byte inneholder færre enn 8 byte dvs. fire 2-byte heltall, ingen tildeling til andre vil bli gjort, og hvis byte inneholder færre enn 6 byte dvs. tre 2-byte heltall, vil ingen oppgave til først bli gjort. Hence. will skrive ut under forutsetning av at hver variabel ikke er angitt tidligere. Det er viktig å merke seg at cs og s og jeg og jeg på 64bit-systemer vil bli skannet inn i lange datastørrelsesverdier. Ved å gjøre dette vil verdier som har sin høye bit satt 0x80 for tegn, 0x8000 for shorts, 0x80000000 for ints, bli signert utvidet. Følgende vil oppstå. Hvis du trenger usignerte verdier, kan du inkludere u flaggkarakteren som følger felttypen. For eksempel, for å lese en usignert kort verdi. Hver type tellerpar beveger en imaginær markør gjennom binære data, leser byte fra gjeldende posisjon Markøren er i utgangspunktet på posisjon 0 i begynnelsen av dataene. Typen kan være en av de følgende tegnene. A Dataene er en byte-streng med lengdetall. Hvis antall er så vil alle de gjenværende bytes i streng bli skannet inn i variabel Hvis teller utelates, blir en byte skannet. Alle bytes skannet tolkes som tegn i området u0000-u00ff, slik at kodingen convertfrom kommandoen vil være nødvendig hvis strengen ikke er en binær streng eller en streng kodet i ISO 8859 -1 For eksempel. vil du returnere 1 med strengen som tilsvarer abcde 000 lagret i var1 og var2 igjen umodifisert, og. vil lagre et euro-valuta tegn i var2.A Dette skjemaet er det samme som en unntatt etterfølgende emner og nuller er fjernet fra den skannede verdien før den er lagret i variablen For eksempel. vil returnere 1 med abc efghi lagret i var1.b Dataene blir omgjort til en streng av telle binære tall i lav til høy rekkefølge representert som en sekvens på 1 og 0 tegn Databytene blir skannet i første til siste rekkefølge med biter tatt i lav til høy rekkefølge innen hver byte. Eventuelle ekstra biter i den siste byten blir ignorert. Hvis telle er så vil alle de resterende biter i streng bli skannet Hvis teller utelates, blir en bit skannet. For eksempel. vil du returnere 2 med 11100 lagret i var1 og 1110000110100000 lagret i var2.B Dette skjemaet er det samme som b bortsett fra at bitene tas i høy til lav rekkefølge innen hver byte For eksempel. vil returnere 2 med 01110 lagret i var1 og 1000011100000101 lagret i var2.H Dataene blir omgjort til en streng med telle heksadesimale sifre i høy til lav rekkefølge representert som en sekvens av tegn i settet 0123456789abcdef Dataene Bytes skannes i første til siste rekkefølge med heksesifrene blir tatt i høy til lav rekkefølge innen hver byte. Eventuelle ekstra biter i den siste byten blir ignorert. Hvis tellingen er, vil alle de gjenværende heksesifrene i strengen bli skannet. Hvis teller er utelatt, vil et heksesiffer bli skannet For eksempel. vil returnere 2 med 07c lagret i var1 og 051f34 lagret i var2.h Dette skjemaet er det samme som H unntatt tallene er tatt i omvendt lav til høy rekkefølge innen hver byte For eksempel. vil du returnere 2 med 706 lagret i var1 og 502143 lagret i var2. Merk at de fleste koden som ønsker å analysere de heksadesimale sifferene fra flere bytes i rekkefølge, skal bruke H-formatet. Dataene blir omgjort til å telle 8-bits signerte heltall og lagret i den tilsvarende variabelen som en liste Hvis telling er så vil alle resterende byte i streng bli skannet. Hvis teller er utelatt, vil et 8-bits heltall bli skannet For eksempel. vil du returnere 2 med 7 -122 lagret i var1 og 5 lagret i var2 Note at heltalene som returneres er signert, men de kan konverteres til deg nsigned 8-biters mengder ved hjelp av et uttrykk like. s Dataene tolkes som telle 16-biters signerte heltal representert i bitendian byte rekkefølge. Tallene er lagret i den tilsvarende variabelen som en liste. Hvis tall er så er alle de resterende byte i strengen blir skannet Hvis teller er utelatt, vil et 16-bits heltall bli skannet. For eksempel. vil du returnere 2 med 5 7 lagret i var1 og -16 lagret i var2 Merk at hele returnerte er signert, men de kan konverteres til usignerte 16-biters mengder ved hjelp av et uttrykk som. Dette skjemaet er det samme som s, bortsett fra at dataene tolkes som telle 16-bits signerte heltal representert i storendisk byteordre. For eksempel. vil du returnere 2 med 5 7 lagret i var1 og -16 lagret i var2.t Dataene tolkes som telle 16-bits signerte heltal representert i den native byte rekkefølge av maskinen som kjører Tcl-skriptet. Det er ellers identisk med s og S For å bestemme hva maskinens native byte rekkefølge er, referer til byteOrder element i tclplatform array i Dataene tolkes som telle 32-bits signerte heltal representert i bitendivale byte rekkefølge Heltalene lagres i den tilsvarende variabelen som en liste. Hvis telle blir så blir alle resterende byte i streng skannet Hvis teller er utelatt, vil et 32-biters heltall bli skannet. For eksempel. vil du returnere 2 med 5 7 lagret i var1 og -16 lagret i var2 Merk at hele returnerte er signert, men de kan konverteres til usignerte 32-biters mengder bruker et uttrykk som. I Dette skjemaet er det samme som jeg, bortsett fra at dataene tolkes som telle 32-bits signerte heltal representert i storendisk byte rekkefølge. For eksempel. vil du returnere 2 med 5 7 lagret i var1 og -16 lagret i var2.n Dataene tolkes som telle 32-bits signerte heltal representert i den innfødte byte rekkefølgen på maskinen som kjører Tcl-skriptet. Det er ellers identisk med i og I For å bestemme hva den innfødte byteordningen til maskinen er, se byteOrder element av tc lplatform array w Dataene tolkes som teller 64-bits signerte heltal representert i bitendivale byte rekkefølge Heltalene lagres i den tilsvarende variabelen som en liste. Hvis telle blir så blir alle de resterende bitene i streng skannet. Hvis teller er utelatt , så blir et 64-bits heltall skannet. For eksempel. vil du returnere 2 med 30064771077 lagret i var1 og -16 lagret i var2 Merk at hele returnerte er signert og ikke kan representeres av Tcl som usignerte verdier. W Dette skjemaet er det samme som w bortsett fra at dataene tolkes som teller 64-bits signerte heltal representert i storendian byte rekkefølge. For eksempel. vil returnere 2 med 21474836487 lagret i var1 og -16 lagret i var2.m Dataene tolkes som teller 64-bit signerte heltal representert i den native byte rekkefølge av maskinen som kjører Tcl skriptet Det er ellers identisk med w og W For å bestemme hva den native byte rekkefølgen til maskinen er, referer til byteOrder elementet i tclplatform array f Dataene er jeg nterpreted som telle enkeltprecisjons flytende punktnumre i maskinens native representasjon. De flytende punktnumrene lagres i den tilsvarende variabelen som en liste. Hvis tellingen blir, blir alle de gjenværende bytene i streng skannet. Hvis teller er utelatt, vil en enkelt - precision flytpunktsnummer vil bli skannet Størrelsen på et flytpunktspunkt kan variere på tvers av arkitekturer, slik at antall byte som skannes, kan variere Hvis dataene ikke representerer et gyldig flytpunktspunkt, er den resulterende verdien udefinert og kompilatoren avhengig For eksempel, på et Windows-system som kjører på en Intel Pentium-prosessor. Vil returnere 1 med 1 6000000238418579 lagret i var1.r Dette skjemaet er det samme som f bortsett fra at dataene er tolket som telle enkelt-presisjon flytpunktnummer i liten endian rekkefølge Denne konverteringen er ikke bærbar til minoriteten av systemer som ikke bruker IEEE flytpunktsrepresentasjoner R Dette skjemaet er det samme som f, bortsett fra at dataene er tolket som c ount enkeltprecisjons flytpunktsnummer i big endian rekkefølge Denne konvertering er ikke bærbar til minoriteten av systemer som ikke bruker IEEE flytpunktsrepresentasjoner d Dette skjemaet er det samme som f, bortsett fra at dataene er tolket som teller dobbelt presisjon flytpunktsnummer i maskinens innfødte representasjon For eksempel vil det på et Windows-system som kjører på en Intel Pentium-prosessor, returnere 1 med 1 6000000000000001 lagret i var1.q Dette skjemaet er det samme som d bortsett fra at dataene er tolket som teller dobbelt presisjon flytende punktnummer i liten endian rekkefølge Denne konvertering er ikke bærbar til minoriteten av systemer som ikke bruker IEEE flytpunktsrepresentasjoner Q Dette skjemaet er det samme som d bortsett fra at dataene er tolket som telle dobbelt-presisjon flytpunktsnummer i big endian rekkefølge Denne konvertering er ikke bærbar til minoriteten av systemer som ikke bruker IEEE flytpunktsrepresentasjoner x Flytter markøren fremover teller byte i streng Hvis tellingen er eller er større t han antall byte etter den nåværende markørposisjonen, så markøren er plassert etter den siste byten i strengen Hvis teller er utelatt, flyttes markøren fremover en byte Merk at denne typen ikke bruker et argument For eksempel vil du returnere 1 med 0304 lagret i var1.X Flytter markøren tilbake teller byte i streng Hvis teller er eller er større enn den nåværende markørposisjonen, er markøren plassert på posisjon 0 slik at neste byte skannes vil være den første byten i streng Hvis teller er utelatt, markøren flyttes tilbake en byte Merk at denne typen ikke bruker et argument For eksempel. vil du returnere 2 med 1 2 lagret i var1 og 020304 lagret i var2. Flytter markøren til den absolutte plasseringen i datastrengen som er oppgitt av teller. Vær oppmerksom på at posisjon 0 refererer til den første byten i strengen. Hvis tall refererer til en posisjon utenfor slutten av strengen, er markøren plassert etter den siste byten. Hvis tellingen utelates, da vil en feil bli generert. For eksempel. vil du returnere 2 med 1 2 lagret i var1 og 020304 lagret i var2. R-r og Q-konverteringene vil bare fungere pålitelig for overføring av data mellom datamaskiner som alle bruker IEEE-flytpunktsrepresentasjoner Dette er veldig vanlig, men ikke universell Hvis du vil overføre flytende poengstall portabelt mellom alle arkitekturer, bruk deres tekstrepresentasjon som produsert av format i stedet. Dette er en prosedyre for å skrive en Tcl-streng til en binærkodet kanal som UTF-8-data foran en lengdeord. Denne prosedyren leser en streng fra en kanal som ble skrevet av den tidligere presenterte writeString-prosedyren. Dette konverterer innholdet til en fil som heter i variabelen filnavn til base64 og skriv ut s them. Numeric Base Converter. Convert tall fra en base til en annen Denne basen konverteren støtter konvertering mellom basene 2 til 36.For baser større enn 10, A 10, B 11, C 12 etc. If i brøkdel av ditt nummer der er en ugyldig inngang, vil delen etter viljen bli ignorert helt. Hvis det er en ugyldig inngang i hele nummerdelen, vil den bruke noe før den ugyldige inntastingen som nummeret ditt. Min alder er 35 i basen 6 Hvor gammel er jeg i base 10.Hvor gammel er jeg i binær Hint binær er base 2.Original Java Applet av Nick Exner 1 15 2001.JavaScript HTML5 Omskrivning av Grant Young 5 29 2014. En metode for koding av binære data for overføring over en seriell link som en ternær kode Binær data mottas og kartlegges i en binær kode. Den binære koden blir oversatt til en ternær kode, og den ternære koden overføres via seriell lenken. Den ternære koden selektivt er invertert i henhold til en forhåndsbestemt protokoll slik at seriekoblingen opprettholder en tid - verdatt null DC b alance. 38. Det som hevdes er 1 En metode for koding av binær data for overføring som ternære data over en seriell lenke, idet fremgangsmåten omfatter trinnene for å motta binære data. mapping av binære data i en binær kode. det bestemmer om ternærkoden er positiv balansert. bestemmer om seriell lenken har en positiv likestrøm likestilling ved å sjekke et tilstandsregister, hvor tilstandsregisteret indikerer at seriell lenken har den positive DC-balansen når tilstandsregistret er i en første tilstand, dersom den ternære koden er positiv balansert. inverterer den binære koden hvis seriekoblingen har den positive DC-balansen og den ternære koden er positiv balansert og translaterer den binære koden inn i den ternære koden. 2. Fremgangsmåte ifølge krav 1, karakterisert ved at trinnet for å bestemme om ternæren koden er positiv balansert, omfatter trinnet for å sjekke en verdi av binære data, hvor den binære koden for binærdata er positiv balansert dersom verdien av binærdata er mindre enn en predeter mined verdi og minst signifikante bit er i en forhåndsbestemt tilstand. 3. Fremgangsmåte ifølge krav 2, karakterisert v e d at den forutbestemte verdi er 245 og den forhåndsbestemte tilstanden er logisk høy. 4. Fremgangsmåte ifølge krav 1, hvor den første tilstanden er logisk høy.5 2. Fremgangsmåte ifølge krav 1, karakterisert v e d at trinnet med å invertere den ternære koden omfatter trinnet med å invertere den binære koden før den binære koden oversettes til den ternære koden. 6. Fremgangsmåte ifølge krav 1, karakterisert ved at den binære data omfatter åtte biter. 7 Fremgangsmåte ifølge krav 6, karakterisert v e d at den binære koden omfatter tolv biter. 8. Fremgangsmåte ifølge krav 7, karakterisert ved at den ternære kode omfatter seks ternære symboler. 9. Fremgangsmåte ifølge krav 8, hvor trinnet med å oversette den binære koden til en ternær kode omfatter trinn for å oversette hver tobitsgruppe av binærkoden til et enkelt ternært symbol.10 En metode for koding av binær data for overføring som ternære data over en seriell lenke, idet fremgangsmåten omfatter trinnene for å motta binære data. mapping av binærdata data til en binær kode. bestemmer om en ternær kode er negativbalansert. bestemmer om seriell lenken har en negativ likestrøm-likningsbalanse ved å sjekke et tilstandsregister, hvor tilstandsregisteret indikerer at seriell lenken har den negative likningsbalansen når statregistret er i en første tilstand hvis den ternære koden er negativbalansert. inverterer den binære koden hvis seriell lenken har den negative DC-balansen og den ternære koden er negativ balansert og. translaterer den binære koden inn i den ternære koden.11 Metoden i henhold til krav 10, karakterisert ved at den første tilstand er logisk høy. 12. Fremgangsmåte for dekoding av en ternær kode mottatt fra en seriell kobling til binære data, hvor fremgangsmåten omfatter trinnene for å motta den ternære kode. translere den ternære koden til en binær kode. bestemme om den ternære koden er nullbalansert. legge inn den binære koden i binære data hvis den ternære koden er nullbalansert. bestemme om den ternære koden er positiv balansert. Seriekoblingen har en null DC-balanse ved å sjekke et tilstandsregister, en første tilstand i statregistret som indikerer null-DC-balansen for seriell lenke, dersom den ternære koden er positiv balansert. Mapping av den binære koden til binære data dersom den ternære koden er positivt balansert og seriekoblingen har null likestilling. bestemmer om den ternære koden er negativbalansert. bestemmer om seriell lenken har en positiv likningsbalanse hvis den ternære koden er negativbalansert. innringer binærkoden hvis seriell lenken har positiv DC-balanse og ternærkoden er negativbalansert og. mapping den binære koden til binære data etter invertering av binærkoden hvis seriell lenken har en positiv DC-balanse og ternærkoden er negativbalansert.13 Fremgangsmåten i krav 12, method further comprising the step of signaling an error if the ternary code is positive balanced and the serial link has the positive DC balance.14 The method of claim 13, the method further comprisin g the step of signaling an error if the ternary code is negative balanced and the serial link has the zero DC balance.15 The method of claim 14, wherein the positive balanced is positive one balanced, and negative balanced is negative one balanced.16 The method of claim 15, the method further comprising the step of signaling the error if the ternary code is not zero balanced, positive one balanced, or negative one balanced.17 The method of claim 12, wherein the first state of the state register is a logic low.18 A binary-to-ternary encoder for encoding binary data for transmission of as a ternary code over a serial link, the binary-to-ternary encoder comprising. a mapping circuit coupled to receive the binary data, the mapping circuit for mapping the binary data to a binary code. a plurality of programmable inverters coupled to the mapping circuit for selectively inverting the binary code in response to an active control signal. encode control circuitry coupled to receive the binary data, the encode control circuitry including a state register for maintaining a state of the serial link, wherein the encode control circuitry enables the plurality of programmable inverters to invert positive balanced binary codes when the state register indicates that a positive binary code has been transmitted, the encode control circuitry for providing the active control signal if the binary code is positive balanced and the serial link has a positive direct current DC balance and. a binary-to-ternary translator coupled to receive the binary code, the binary-to-ternary translator for translating the binary code into the ternary codes.19 The binary-to-ternary data encoder of claim 18, wherein the plurality of programmable inverters act do not invert the binary code when the control signal is inactive.20 The binary-to-ternary encoder of claim 18, wherein the control signal is active high and each of the plurality of programmable inverters is an XOR gate having the control signal as one inp ut.21 The binary-to-ternary encoder of claim 18, wherein the control signal is active low and each of the plurality of programmable inverters is an XNOR gate having the control signal as one input.22 The binary-to-ternary encoder of claim 18, wherein each of the plurality of programmable inverters includes a buffer and driver, the buffer and the driver being coupled to receive the control signal such that only one of the buffer and the driver is enabled to output a portion of the binary code.23 The binary-to-ternary encoder of claim 18, wherein the mapping circuit comprises combinational logic.24 The binary-to-ternary encoder of claim 18, wherein mapping circuit comprises a look-up table.25 The binary-to-ternary encoder of claim 18, wherein the binary-to-ternary translator comprises. an OR gate coupled to receive a first bit of a binary code and a second bit of the binary code. an AND gate coupled to receive the first bit and the second bit. a digital to analog converter DAC coupled to re ceive outputs of the OR and AND gates. a level shifter coupled to receive an output of the DAC, the level shifter for generating ternary voltage levels in response to the output of the DAC.26 A ternary-to-binary decoder for decoding ternary data received from a serial link into binary data, the ternary-to-binary decoder comprising. a ternary-to-binary translator coupled to the serial link, the ternary-to-binary translator for translating a ternary code into a binary code. a mapping circuit coupled to the ternary-to-binary translator, the mapping circuit for mapping the binary code into binary data and. decode control circuitry coupled to the ternary-to-binary translator, the decode control circuitry including a state register for indicating a state of the serial link, the state register being set to a first state if a previously received binary code was positive balanced, the decode control circuitry providing the active control signal if the binary code is positive balanced and the state register is in the first state, the decode control circuitry for providing the active control signal if the binary code is positive balanced and a previously received binary code was positive balanced.27 The ternary-to-binary decoder of claim 26, wherein the ternary-to-binary decoder further comprises. a plurality of programmable inverters coupled between the ternary-to-binary translator and the mapping circuit, the plurality of programmable inverters for inverting the binary code in response to an active control signal.28 A computer network comprising. a serial link for transmitting ternary data. a first node coupled to the serial link, the first node including a first circuit that operates using binary data and a binary-to-ternary encoder for encoding binary data received from the first circuit for transmission of a ternary code over the serial link, wherein the binary-to-ternary data encoder comprises. a mapping circuit coupled to receive the binary data, the mapping circuit for mapping the binary data to a binary code. a plurality of programmable inverters coupled to the mapping circuit for selectively inverting the binary code in response to an active control signal. encode control circuitry coupled to receive the binary data, the encode control circuitry including a state register for maintaining a state of the serial link, wherein the encode control circuitry enables the plurality of programmable inverters to invert positive balanced binary codes when the state register indicates that a positive binary code has been transmitted, the encode control circuitry for providing the active control signal if the binary code is positive balanced and the serial link has a positive direct current DC balance and. a binary-to-ternary translator coupled to receive the binary code, the binary-to-ternary translator for translating the binary code into the ternary code. a second node coupled to the serial link, the second node including a second circuit that operates using the binary data and a ternary-to-binary decoder for decoding ternary codes received from the serial link into binary data for the second circuit.29 The computer network of claim 28, wherein the plurality of programmable inverters do not invert the binary code when the control signal is inactive.30 The computer network of claim 28, wherein each of the plurality of programmable inverters includes a buffer and an inverter, the buffer and the inverter being coupled such that only one of the buffer and the inverter is enabled to output a portion of the binary code.31 The computer network of claim 28, wherein the control signal is active high and each of the plurality of programmable inverters is an XOR gate having the control signal as one input.32 The computer network of claim 28, wherein the control signal is active low and each of the plurality of programmable inverters is an XNOR gate having the control signal as one input.33 The computer network of claim 28, wherein the mapping circuit comprises combinational logic.34 The computer network of claim 28, wherein mapping circuit comprises a look-up table.35 The computer network of claim 28, wherein the binary-to-ternary translator comprises. an OR gate coupled to receive a first bit of a binary code and a second bit of the binary code. an AND gate coupled to receive the first bit and the second bit. a digital to analog converter DAC coupled to receive outputs of the OR and AND gates. a level shifter coupled to receive an output of the DAC, the level shifter for generating ternary voltage levels in response to the output of the DAC.36 The computer network of claim 28, wherein the ternary-to-binary decoder comprises. a ternary-to-binary translator coupled to the serial link, the ternary-to-binary translator for translating the ternary code into the binary code. a second mapping circuit coupled to the ternary-to-binary translator, the second mapping circuit for mapping the binary code into binary data.37 The ternary-to-binary decoder of cl aim 36, wherein the ternary-to-binary decoder further comprises. a second plurality of programmable inverters coupled between the ternary-to-binary translator and the second mapping circuit, the second plurality of programmable inverters for inverting the binary code in response to an active control signal. decode control circuitry coupled to the ternary-to-binary translator and the second plurality of programmable inverters, the decode control circuitry for providing the active control signal if the binary code is positive balanced and a previously received binary code was positive balanced.38 The ternary-to-binary decoder of claim 37, wherein the decode control circuitry includes a second state register for indicating a state of the serial link, the second state register being set to a first state if a previously received binary code was positive balanced, the decode control circuitry providing the active control signal if the binary code is positive balanced and the state register is in the first state. BACKGROUND OF THE INVENTION.1 Field of the Invention. The present invention relates generally to the encoding of data for transmission over a serial link and more particularly to the binary-to-ternary encoding and decoding of data transmitted over twisted-pair wire.2 Art Background. Prior art local area networks LANs such as Ethernet typically utilize serial links for the transmission of binary data between nodes Typical examples of prior art serial links are coaxial cable and twisted-pair wire Transmission of digital data over the serial link is accomplished by varying the analog voltage levels of the serial link One concern of transmitting data over such serial links is maintaining the reliable determination of transmitted data in view of the capacitance of the serial link itself Because the conductor of the serial link acts as a capacitor, care must be taken to ensure that no charge is stored in the serial link If the serial link is allowed to store charge, the tran smitted data may be incorrectly sensed. A typical prior art method for ensuring that there is no charge stored in the serial link of the LAN is Manchester encoding Manchester encoding ensures that in any given packet or frame of transmitted data, the number of logic O s transmitted and the number of logic 1 s transmitted are equal This equality is termed zero-balanced Zero-balanced coding schemes ensure that the net charge, or direct current DC balance of the serial link is zero. One limitation of Manchester encoding schemes is that Manchester encoding requires a doubling of the bandwidth for the serial link When the desired bandwidth of the LAN is very high, e g 100 MBp s, and the serial link is twisted-pair, Manchester encoding cannot be supported This is because twisted-pair cannot support a bandwidth of 200 MBp s over a significant distance, e g 100 meters Therefore, Manchester encoding cannot be used in all situations However, Manchester encoding has attributes that are important to reliably transmit data over serial links Specifically, it is desirable that the DC balance of the serial link be maintained at zero Therefore, a new encoding system for transmitting zero DC balanced data over a high bandwidth LAN is required. SUMMARY AND OBJECTS OF THE INVENTION. One object of the present invention is to provide for the time-averaged zero DC-balance of the serial link. Another object of the present invention is to provide a binary-to-ternary encoder that encodes binary data as ternary data for transmission over a serial link. Another object of the present invention is to provide a ternary-to-binary decoder for decoding ternary data received from a serial link. These and other objects of the invention are provided for by a method for encoding binary data for transmission over a serial link as a ternary code Binary data is received and mapped into a binary code The binary code is translated into a ternary code, and the ternary code is transmitted over the serial link The ter nary code is selectively inverted according to a predetermined protocol such that the serial link maintains a time-averaged zero DC balance. Other objects, features, and advantages of the present invention will be apparent from the accompanying drawings and from the detailed description which follows below. BRIEF DESCRIPTION OF THE DRAWINGS. The present invention is illustrated by way of example and not limitation in the figures of the accompanying drawings, in which like references indicate similar elements, and in which. FIG 1 shows a computer network according to one embodiment. FIG 2 shows a single node of a computer network according to one embodiment. FIG 3 shows an adapter of a computer network node according to one embodiment. FIG 4 shows an binary-to-ternary encoder. FIG 5 shows a binary-to-ternary translator. FIG 6 is a flow chart showing an encoding method according to one embodiment. FIG 7 shows a ternary-to-binary decoder. FIG 8 shows a ternary-to-binary translator. FIG 9 shows a port ion of the decoding mapping logic. FIG 10 shows a decoding method. FIG 11A shows a programmable inverter. FIG 11B shows a programmable inverter. FIG 11C shows a programmable inverter. The following description provides numerous specific details and examples Further, the figures that accompany the description contain further details that are intended to assist the reader in better understanding the features, advantages and construction of the present invention These details and examples are provided for illustrative purposes only, and should not be regarded as exhaustive of the ways in which the teachings of the present disclosure may be modified or applied. The method and apparatus for encoding and decoding binary data to ternary data as described herein are of particular use in high-speed Ethernet local area networks that operate at 100 MBp s a standard for which is currently under development by the Institute of Electrical and Electronics Engineers IEEE The developing standard supplements the ANSI IEEE 802 3 standard The current designation for the supplement is 100 BASE-4T. FIG 1 shows a computer network 100 according to a first embodiment Serial link 105 is coupled to nodes A, B, C and D, for the transmission of data between each of the nodes In this embodiment, the serial link 105 is preferably twisted-pair wire, although it may be coaxial cable or any equivalent conductor The computer network 100 is designed to transmit ternary, or tri-level data over the serial link 105 The nodes A, B, C and D are preferably designed to operate using standard binary data Thus, each of the nodes A, B, C and D include encoders and decoders for interfacing with and transmitting data over the serial link 105.FIG 2 shows node A in further detail FIG 2 is illustrative of each of the nodes connected to serial link 105 In essential terms, node A includes an adapter 205 and a computer system 207 The adapter 205 is coupled both to the serial link 105 and to the computer system 207 The adapter 205 contains circuitry necessary to encode data received from the computer system 207 and to transmit the encoded data over the serial link 105 The adapter 205 also contains circuitry necessary to receive encoded data from the serial link 105 and to decode the encoded data For example, the adapter 205 may be a media access controller MAC constructed according to one of the various 802 LAN standards promulgated by the Institute of Electrical and Electronic Engineers IEEE. In addition to encoding data from the binary representation of the computer system 207 to the ternary representation of the serial link 105, the adapter 205 must also be capable of translating data from a parallel form to a serial form This is typically true when the adapter is coupled to the system bus of the computer system 207, which typically operates through the parallel transmission of data The computer system 207 may be, for example, a personal computer having a CPU, main memory and a display device The adapter 205 may be physically incorporated in the computer system 207 as an adapter board coupled to a slot in the bus for the computer system 207.FIG 3 shows the adapter 205 for node A in greater detail The adapter 205 includes a system interface 305 for receiving data from the computer system 207 and for receiving data from the transceiver controller 307 The transceiver controller 307 is typically responsible for the managing incoming and outgoing data for node A The network interface 309 is for interfacing with the serial link 105 The circuitry of the present invention, as described below, may be disposed within any one of these functional units Typically, however, the circuitry of the present embodiments is disposed within the network interface block 309 Thus, network interface 309 is shown as including binary-to-ternary encoder 311 and ternary-to-binary decoder 312.As described above, the serial link 105 operates using tri-level encoding This means that data is transmitted over the serial link 105 by varying the voltage level of the serial link 105 to be one of three possible analog voltages The largest of the three analog voltage levels preferably corresponds to a ternary logic 1, the intermediate analog voltage level preferably corresponds to a ternary logic 0, and the smallest analog voltage level preferably corresponds to a ternary logic -1 The preferred analog voltage levels of the present embodiment are 3 5 volts for ternary logic 1, 0 0 volts for ternary logic 0, and -3 5 volts for ternary logic -1 Using ternary analog voltage levels for transmitting data over the serial link 105 allows for a time average zero-balance for the transmission of data without a corresponding increase in bandwidth requirements for the serial link 105 Tri-level encoding also results in an overall compression of the original binary data For example, only six ternary bits are required to express eight binary bits. According to the present embodiment, the adapter 205 encodes eight binary b its of data received from the computer system 207 into six ternary bits of data for transmission over the serial link 105 The amount of data to be encoded may be varied according to the protocols and transmission requirements of the network in which the encoder is implemented The present embodiment contemplates the serial-to-parallel conversion of the data taking place within the encoder Alternatively, parallel-to-serial conversion may occur prior to data being received from the computer system 207 For the purposes of illustration, a binary-to-ternary encoder 311 is shown as being disposed within the network interface 309.For LANs, data transmission over the serial link typically occurs in a packet-switched manner For example, in Ethernet a transmitting node transmits a packet or frame of data having at least sixty-four binary bytes of data Manchester encoding ensures that a zero DC balance is maintained for the serial link between transmission of flames of binary data A goal of the pr esent embodiment is to similarly maintain a time-averaged zero DC balance for the serial link without using Manchester encoding. For the present encoding scheme, every eight binary bits to be encoded as ternary data are first mapped to a binary code having twelve binary bits There are a total of 256 binary codes, one binary code for each possible combination of eight binary bits of data Each binary code is divided into six groups of two binary bits, and each of the six groups of two binary bits are translated into a ternary symbol according to the simple binary-to-ternary translations of Table 1 such that a six ternary symbol code results The six ternary symbol code is then transmitted over the serial link 105.Table 1 shows one of thirty possible complete, non-unique translations between two binary bits and one ternary symbol Wherein alternative translations may be utilized, the specific translations shown are chosen to further the goal of providing a time-averaged zero DC balance Speci fically, as will be described in greater detail below, the encoder 311 inverts each bit of the twelve bit binary code in the appropriate circumstances The translations of Table 1 provide that inversions of the binary code produces a corresponding inversion in the ternary symbol In practice, the binary codes utilize only one of the two binary expressions of the 0 ternary symbol For the present embodiment, each group of two bits of a binary code can be either 00 , 10, or 11.Appendix A shows one mapping table of ternary codes for all possible combinations of eight bit binary data according to the present embodiment In light of the translations of Table 1, Appendix A also inherently shows the binary codes The 256 ternary codes are all either zero-balanced or 1 balanced positive balanced In other words, the sum of the ternary symbols for every ternary code is equal to either zero or positive one Alternatively, -1balanced negative balanced ternary codes in which the sum of the six ternary sy mbols is equal to negative one may be used As shown, the ternary codes for data bytes having a value between 0 to 244 are arranged in a sorted manner such that even bytes bytes which have a logic 0 at the least significant bit position are assigned zero-balanced codes and odd bytes bytes which have a logic 1 at the least significant bit position are assigned positive balanced codes Those bytes having a value greater than 244 are assigned zero-balanced codes Further, each ternary code contains at least two transitions and has no more than three leading or trailing 0 symbols The ternary codes are self-clocking codes in which the timing is incorporated into the signal itself to obviate the need for a separate docking channel The previous two features of the ternary codes are included to better ensure that no loss of synchronization occurs between nodes For networks that do not use self-docking codes, these two features are not required. To achieve a time-averaged zero DC balance for the se rial link 105, the binary-to-ternary encoder 311 inverts positive balanced ternary codes as necessary to produce negative balanced codes When a first positive balanced code is transmitted, the next positive balanced code to be transmitted is inverted to produce a negative balanced code Any intervening zero-balanced codes are not inverted In this manner, the number of ternary positive and negative 1 s transmitted will be equal over time, resulting in a time-averaged zero DC balance for the serial link 105.It should be noted that the encoding scheme may be implemented using alternative mapping tables The ternary codes need not be limited to zero, 1, and -1balanced codes However, the mapping table of Appendix A is advantageous as it results in relatively simple circuit implementations Further, the tri-level encoding scheme of binary data of the present embodiment may be adapted according to the specific protocols and system needs of a particular communication system When applying a tri-le vel encoding scheme to systems that encode more than or less than eight binary bits of data at a time, such factors as speed of encoding, speed of decoding, speed of transmission and the time-averaged DC balance of the serial link must be balanced according to the needs of the particular system. FIG 4 shows binary-to-ternary encoder 311 in greater detail Binary-to-ternary encoder 311 includes mapping circuit 410, encode control circuitry 412, programmable inverters 418 and binary-to-ternary translator 420 Mapping circuit 410 maps an incoming binary byte into a corresponding twelve bit binary code according to the mapping table of Appendix A Mapping circuit 410 is preferably comprised of combinational logic to reduce hardware costs The specific combinational logic gates used may be selected by a designer using techniques that are well known in the art such that a given input byte of data yields a corresponding output binary code Alternatively, mapping logic 410 may be comprised of a prog rammable logic array PLA , programmable array logic PAL , a programmable logic device PLD , or a look-up table A look-up table may be implemented using random access memory RAM or read only memory ROM. Encode control circuitry 412 is coupled to receive the incoming eight bits of data The encode control circuitry 412 determines when a positive balanced code is to be mapped by the mapping circuit 410 by checking the value of the incoming byte of data If the incoming byte is less than 245 and has a lowest significant bit of logic 1, the code is positive balanced Of course, this checking scheme is dependent on the code table and binary-to-ternary translation implemented A checking scheme that is independent of the implemented code table and translation scheme would require checking the balance of the ternary code after the translation from the binary code. Encode control circuitry 412 determines whether to invert a positive balanced code by checking the state of a state register 415 The stat e register 415 is one binary bit wide and is initialized to a binary logic 0 The encode control circuitry 412 increments the state register 415 by one when a first positive balanced code is mapped The next positive balanced code that is mapped is inverted, and the encode control circuitry 412 resets the state register 415 to zero. Encode control circuitry 412 provides output control signals via signal lines 417 to the programmable inverters 418 to enable and disable the programmable inverters 418 The programmable inverters 418 act as inverters when enabled and as non-inverting buffers when disabled Each programmable inverter 418 may be implemented as a two-input exclusive OR XOR gates if a logic high control signal enables the programmable inverters 418 i e the control signal is an active high signal Each programmable inverter 418 may alternatively be implemented as a two-input exclusive NOR XNOR gate if a logic low control signal enables the programmable inverters 418 i e the control s ignal is an active low signal Further, each programmable inverter 418 may include a buffer and an inverter, each of which receives the control signal and only one of which is enabled at any one time These possibilities are shown in FIGS 11A, 11B, and 11C below A programmable inverter 418 is provided for each output of the mapping circuit 410 For example, wherein the output of the mapping circuit 410 is twelve bits, there are twelve programmable inverters 418.An alternative method for providing inverted binary codes requires that the mapping circuit contains two maps, a non-inverted map and an inverted map The inverted map contains inverted binary codes that are mapped to the same binary data The encode control circuitry 412 is coupled to the mapping circuit 410 for selecting the map to be used The encode control circuitry 412 makes the selection according to the criteria detailed above. FIG 5 shows a portion of a binary-to-ternary translator in greater detail Binary-to-ternary translato r 420 translates one of the two bit groups of the twelve bit binary code according to the translation table of Table 1 Binary-to-ternary translator 420 includes OR gate 510, AND gate 515, digital-to-analog converter DAC 520, and tri-level output buffer 530 Two bits of a binary code are received by the OR gate 510 via signal lines 501 and 502 OR gate 510 and AND gate 515 are configured such that a 10 is output if the two bits are not the same Equivalent logic circuits may be employed Signal line 501 carries the more significant bit, bit x b and signal line 502 carries the less significant bit, bit Y b The outputs of OR gate 510 and AND gate 515 are coupled as inputs to DAC 520 DAC 520 drives the tri-level output buffer 530 to output tri-level analog voltage levels The V1 supply provides the positive side voltage, and the V2 supply provides the negative side voltage The circuitry shown in FIG 5 is preferably replicated for each two bit group of the twelve binary bit code A single DAC hav ing six outputs may be used Also included, but not shown, is a parallel-to-serial converter for sequencing the six ternary symbols output by the DAC 520.FIG 6 is a flow chart illustrating the method utilized by the binary-to-ternary encoder 311 At step 600, eight bits of binary data are provided by the computer system 207 to the binary-to-ternary encoder 311 At step 605, the binary-to-ternary encoder 311 determines if the binary code for the incoming eight bits of binary data is a nonzero balanced code For one embodiment, this is done by checking the incoming eight bits rather than by checking the binary code If the value of the incoming eight bits is less than 245 and the least significant bit is a logic 1, the binary code is not zero-balanced. At step 610, if the binary code is zero balanced, the binary-to-ternary encoder 311 encodes the eight bits of binary data according to the above-described limitations Similarly, the eight bits are mapped to the binary code at step 615 if the cod e is non zero balanced The decisional step 605 may occur after mapping occurs in response to either the binary data or the binary code. At step 620, the binary-to-ternary encoder 311 determines if there is a nonzero balance on the serial link by referring to a memory element such as state register 415 If the state register 415 is not set at step 620, the flow continues at step 625, where the state register is set to indicate that the serial link 105 is not zero-balanced If the state register 415 was previously set, the flow proceeds to step 630, where the binary-to-ternary encoder 311 inverts the binary code and resets the state register 415 For this embodiment, the state register has only two possible states In this manner, the time-averaged DC balance of the serial link 105 is a zero DC balance. After the incoming byte of data is coded into the twelve binary bit code at steps 610, 625, or 630, the binary-to-ternary encoder 311 translates the binary code into an equivalently balanced te rnary code This may be done according to the truth table of Table 1 using the binary to ternary translator circuitry shown in. FIG 5 The ternary code is transmitted at step 640.FIG 7 shows a ternary-to-binary decoder according to one embodiment As shown, the ternary-to-binary decoder 312 includes ternary-to-binary translator 720 and decode mapping circuit 730, which includes decode control circuitry 735 The ternary-to-binary translator 720 receives six ternary symbols in a serial manner and translates them into a twelve bit binary code having a parallel format The twelve bit binary code is then forwarded to the decode mapping circuit 730 Decode control circuitry 735 within the mapping logic 730 determines whether an error has occurred in transmission and whether the translated binary code must be inverted If an error has occurred in transmission, the decode mapping circuit 730 signals an error to the computer system 207 If no error has occurred, the decode mapping circuit 730 maps the t welve bit binary code into the eight bit data and forwards it to the computer system 207.FIG 8 shows the ternary-to-binary translator 720 in greater detail The ternary-to-binary translator 720 includes two differential comparators 805 and 810 The ternary symbol received from the serial link 105 is coupled to the positive inputs of the differential comparators 805 and 810 The negative terminal of comparator 805 is coupled to a reference supply V ref1 which preferably corresponds to a voltage between the voltages for ternary 0 and ternary -1 For example, where the analog voltage for a ternary -1is equal to -3 5 volts, and the analog voltage for ternary symbol 0 is 0 0 volts, an appropriate voltage for V ref1 is -1 0 volts The comparator 810 preferably has its negative terminal coupled to a reference voltage supply V ref2 When the analog voltage for a ternary symbol 1 is equal to 3 5 volts, V ref2 is preferably equal to 1 0 volts. The outputs of differential comparators 805 and 810 are bot h fed as inputs to OR gate 815 and AND gate 820 The OR gate 815 outputs the more significant bit of a two bit group, x b The AND gate 820 outputs the less significant bit of a two bit group, Y b The outputs of this portion of the ternary-to-binary translator may be fed serially to a first-in-first-out FIFO buffer that outputs twelve binary bits in parallel to achieve the desired serial to parallel conversion The necessary control circuitry and the data buffer memory is preferably provided in the ternary-to-binary translator 720.FIG 9 shows a portion of the decode mapping circuit 730 The data buffer memory 905 is preferably that discussed in relationship to the ternary-to-binary translator of FIG 8 As shown, two bits are received by data buffer memory 905 and 12 bits are output by data buffer memory 905 Associated with each contiguous pair of output lines of the data buffer memory 905 is an XOR gate 910 and an AND gate 915 Also coupled to each output line is a programmable inverter 925 which acts as described above The programmable inverters 418 for each contiguous pair of output lines are controlled by a single control line from decode control circuitry 735 Thus, there are a total of six XOR gates 910, six AND gates 915, twelve programmable inverters 418, and six control lines 917.The decode control circuitry 735 counts the total number of logic 1 s and the total number of logic 0 s received from the outputs of the AND gates 915 The decode control circuitry 735 compares the total number of logic 0 s to the total number of logic 1 s to determine if a transmission error has occurred A transmission error has occurred if the balance of a received ternary code is incorrect in view of the known state of the serial link 105 and the encoding scheme The decode control circuitry 735 only counts the outputs of an AND gate 915 if the corresponding XOR gate 910 of the contiguous pair of output lines outputs a logic 0, which signifies that the both bits of the contiguous pair of output lines are the same As seen in Table 1, this corresponds to either ternary -1or ternary 1 The binary bits corresponding to a ternary 0 symbol are not considered because they do not affect the balance of the ternary code In this manner, the balance of the ternary code is determined. If the total number of logic 0 s is equal to the total number of logic 1 s, the ternary code is zero-balanced and the decode control circuitry 735 signals the remainder of the mapping logic to map the twelve binary bits to the eight binary bit data The programmable inverters 418 are disabled. If the total number of logic 1 s exceeds the total number of logic 0 s by one, the decode control circuitry 735 checks the state register 920 If the state register 920 is set to a logic 0, the decode control circuitry 735 sets the state register to a logic one and signals the remainder of the mapping logic to map the binary code to binary data If the state register is set to a logic one, an error is signaled by the decode control circuitry 735.If the total number of logic 0 s is greater than the total number of logic 1 s by one, the decode control circuitry 735 checks the state register 920 If the state register is set to a logic 1, the decode control circuitry 735 resets the state register 920 to logic 0 and enables the programmable inverters 418 to cause the inversion of the outputs from the data buffer memory 905 The decode control circuitry 735 only enables those programmable inverters 418 associated with a contiguous pair of output lines in which both bits are the same If the output of the XOR gate 915 for a contiguous pair of output lines is a logic 1, the associated programmable inverters are disabled The decode control circuitry 735 outputs an error signal if the total number of logic 0 s is greater than the number of logic 1 s by one when the state register is set to logic 0.The decode control circuitry 735 also signals an error if the total number of logic 0 s exceeds the total number o f logic 1 s by more than one Similarly an error signal is generated if the total number of logic 1 s exceeds that total number of logic 0 s by more than one. FIG 10 shows the method of the ternary-to-binary decoder according to one embodiment At step 1000, 6 ternary symbols are received by the ternary-to-binary decoder 312 At step 1005, the ternary-to-binary translation occurs such that the 6 ternary symbols are translated into a twelve bit binary code At step 1010, it is determined whether the ternary code is zero balanced If the ternary code is zero-balanced, the decode mapping circuit 730 translates the twelve bit binary code to the eight bit binary data at step 1015 If the ternary code is not zero-balanced, it is determined whether the ternary code is positive balanced at step 1020 If the ternary code is positive balanced, at step 1025 it is determined whether the state bit of the state register is equal to logic 0 If the state bit is not equal to logic 0, an error is signaled at st ep 1026 If the state bit is equal to zero, the state bit is set to be equal to one at step 1030 The binary code is mapped to binary data at step 1035.If the ternary code is not positive balanced at step 1020, it is determined whether the ternary code is negative balanced at step 1040 If the ternary code is not negative balanced, an error is signaled at step 1041 because the balance is greater that 1 balanced If the ternary code is negative balanced, it is determined at step 1045 whether the state bit is equal to logic 1 If the state bit is not equal to logic 1, an error is signaled at step 1046 If the state bit is equal to logic 1, the state bit is reset to zero and the appropriate portions of the binary code are inverted at step 1050 The binary code is mapped to binary data at step 1055.FIGS 11A-11C show various alternative embodiments for the programmable inverters FIG 11A shows a programmable inverter 418 as a buffer 1105 and an inverter 1110, each of which is coupled to receive the same input and control signal Both the buffer 1105 and the inverter 1110 are enabled by the control signal, but the enable input of the buffer 1105 is inverted such that only one of the buffer 1105 and the inverter 1110 is enabled at any one time FIG 11B shows a programmable inverter 418 as an XOR gate 1115 having one input coupled to receive the control signal and a second input coupled to receive an input FIG 11C shows a programmable inverter 418 as an XNOR gate 1120 having one input coupled to receive the control signal and a second input coupled to receive an input The inputs for each of the various programmable inverters 418 may be received from the mapping logic 410 or the data buffer memory 905.In the foregoing specification the invention has been described with reference to specific exemplary embodiments thereof It will, however, be evident that various modifications and changes may be made thereto without departing from the broader spirit and scope of the invention as set for th in the appended claims. Binary numbers. A computer number system that consists of 2 numerals, 0 and 1 It is sometimes called base-2 Since computers do not have 10 fingers, all the counting within the computer itself is done using only 2 numerals 0 and 1 or on and off or false and true. Hexadecimal numbers. The hexadecimal system hex for short uses numbers from 0 to 15 It starts off like the decimal system 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 but then comes A which equals 10 and then B, C, D, E and F which of course equals 15 The next number is 10 which is actually 16 in decimal and so on Because it can be impossible to distinguish between a hex and a decimal number is that 25 a decimal 25 or is it 25 in hex which equals 37 decimal it is customary to put a lowercase h after each hex number So 25 is a decimal number and 25h is a hex one. ASCII stands for American Standard Code for Information Interchange It is a standard that was defined in 1963 to allow computers to exchange information, regar dless of the manufacturer. Since computers basically work numbers based, the ASCII character set consists of 128 decimal numbers, ranging from 0 through 127, assigned to letters, numbers, punctuation marks and the most common special characters Since a computer needs 7 bits to represent the numbers 0 to 127, these codes are sometimes referred to as 7-bit ASCII. Numbers 0 to 31 are used for control codes special instructions such as indicating that the computer should make a sound ASCII code 7 or the printer should start from a new sheet of paper ASCII code 12.ASCII codes 32 to 47 are used for special characters, starting with the space character. After the numbers 0 to 9 ASCII codes 48 to 57 you once again get some special characters, from the colon to the symbol. The letters start with the capital A from ASCII code 65 onwards The lowercase a to z characters take up ASCII codes 97 to 122 You may wonder why the lowercase characters don t simply follow their capital brethren Remember this is ASCII, this is computer stuff from the dark ages If you take a capital U, which is ASCII code 85, and add 32 to that code, you get character code 117, which is the lowercase u 32 is the magic distance between any upper and lower case character and 32 is a truly magical, efficient number that any computer or nerd can relate to Even I love 32.Codes 123 to 127 are once again special characters, including the tilde. All computer systems also use numbers 128 through 255 to represent additional characters, but this list is not really universally standardized That is why the above table is split up in two parts The first table with the 7-bit ASCII codes is universal across all computers The second extended ASCII table is not it is what current Windows machines use. Because 256 characters are not sufficient to represent all characters used in Asian languages and to solve the annoying compatibility problems with different codes being used for codes 128 to 255, a new standard has emerged The Unic ode character set contains more than 32000 characters.30 December 2016.thank you that was so helpful. The Commodore-64 fully utilized the ascii characters beyond 128 dec with on board keyboard keys with symbols of block shaping and different iner-shapes to be used for programing grphic design in basic comouter language Also giving it the ability to form different letter shapes for other language scripts Using basic OS you could use it in any country Also fat-tracking was designed so the 1541 drive was able to deliver units of 12bit information chuncks making the drive run hot and constant when disc active games arrived So it seems fair to say I am right when I say few people know or are aware that there was a beast of a computer that made all others look hack, sad and incompetent Apple and IBM constructs and programming was second rate All inginuity came from enthusiasts not money hungry cluelessness Apple was a lot but so much less because us computer heads were running the show Thanx for the table and try and talk to a c-64 owner and listen to what they say. Jess Antonio says. El nmero 7 en sistema binario es igual a 111, ya que 7 dividido entre 2 es igual a 3, y sobra 1 despus la mitad de 3 es 1 entre dos es 1 despus 1 entre 2 es igual a 1 Finalmente los residuos son 111, siendo ste el resultado que es igual a 111.please tell me how we canfind binary 7 screm in code a to z lowerand upper case. Hi, based on examples above I have mixed class IPFilter with netMatch function wich gives me complete class for IP4 check including CIDR IP format. php class IP4Filter. private static IPTYPESINGLE single private static IPTYPEWILDCARD wildcard private static IPTYPEMASK mask private static IPTYPECIDR CIDR private static IPTYPESECTION section private allowedips array. public function construct allowedips this - allowedips allowedips. public function check ip allowedips null allowedips allowedips allowedips this - allowedips. foreach allowedips as allowedip type this - judgeiptype allowedip subrst calluserfunc array this subchecker type , allowedip ip. private function judgeiptype ip if strpos ip return self IPTYPEWILDCARD. if strpos ip tmp explode ip if strpos tmp 1 , return self IPTYPEMASK else return self IPTYPECIDR. if strpos ip - return self IPTYPESECTION. if ip2long ip return self IPTYPESINGLE. private function subcheckersingle allowedip ip return ip2long allowedip ip2long ip. private function subcheckerwildcard allowedip ip allowediparr explode allowedip iparr explode ip for i 0 i count allowediparr i if allowediparr i return true else if false allowediparr i iparr i return false. private function subcheckermask allowedip ip list allowedipip allowedipmask explode allowedip begin ip2long allowedipip ip2long allowedipmask 1 end ip2long allowedipip. ip2long allowedipmask 1 ip ip2long ip return ip begin ip end. private function subcheckersection allowedip ip list begin end explode - allowedip begin ip2long begin end ip2long end ip ip2long ip return ip begin ip end. private function subcheckerCIDR CIDR IP list net mask explode CIDR return ip2long IP. 1 32 - mask - 1 ip2long net. For me this code works great, so I wanna thank to all You guys. To get the network adress out of the broadcast adress and netmask just to an AND on it. php simple example bcast ip2long 192 168 178 255 smask ip2long 255 255 255 0 nmask bcast smask echo long2ip nmask Will give 192 168 178 0.With this example you are able to check if a given host is in your own local net or not on linux. php Check if a client IP is in our Server subnet param string clientip param string serverip return boolean function clientInSameSubnet clientip false serverip false if clientip clientip SERVER REMOTEADDR if serverip serverip SERVER SERVERADDR Extract broadcast and netmask from ifconfig if p popen ifconfig r return false out while feof p out fread p 1024 fclose p This is because the comment function does not allow long lines match serverip match Bcast d d i d d match Mask d d d d im if pregmatch match out regs return false bcast ip2long regs 1 smask ip2long regs 2 ipadr ip2long clientip nmask bcast smask return ipadr smask nmask smask. In 32bits systems, you cannot convert ipv6 to long, but you can convert ip2bin and bin2ip. This function converts ipv4 and ipv6, returns false if ip is not valid. php function ip2bin ip if filtervar ip FILTERVALIDATEIP FILTERFLAGIPV4 false return baseconvert ip2long ip , 10 2 if filtervar ip FILTERVALIDATEIP FILTERFLAGIPV6 false return false if ipn inetpton ip false return false bits 15 16 x 8 bit 128bit ipv6 while bits 0 bin sprintf 08b , ord ipn bits ipbin bin ipbin bits -- return ipbin. function bin2ip bin if strlen bin 32 32bits ipv4 return long2ip baseconvert bin 2 10 if strlen bin 128 return false pad 128 - strlen bin for i 1 i pad i bin 0 bin bits 0 while bits 7 binpart substr bin , bits 16 , 16 ipv6 dechex bindec binpart bits return inetntop inetpton substr ipv6 0 ,- 1.here is netMatch function which is the fastest I could wrote, I hope developers will include native function soon. php function netMatch CIDR IP list net mask explode CIDR return ip2long IP. 1 32 - mask - 1 ip2long net. php function CalculateIPRange iprange Daevid Vincent 10 13 03 This function will return an array of either a negative error code or all possible IP addresses in the given range format is - spaces are okay. temp pregsplit - iprange - 1 PREGSPLITNOEMPTY QRange1 temp 0 QRange2 temp 1.if QRange2 return array QRange1 special case, they didn t put a second quad parameter. basic error handling to see if it is generally a valid IP in the form N N N N if pregmatch d d d d QRange1 1 return array - 1 if pregmatch d d d d QRange2 1 return array - 1. quad1 explode QRange1 quad2 explode QRange2.reset quad1 while list key val each quad1 quad1 key intval val if quad1 key 0 quad1 key 255 return array - 2 reset quad2 while list key val each quad2 quad2 key intval val if quad2 key 0 quad2 key 255 return array - 2. startIPlong sprintf u ip2long QRange1 endIPlong sprintf u ip2long QRange2 difference endIPlong - startIPlong echo startIPlong startIPlong and endIPlong endIPlong difference difference BR. ip array k 0 for i startIPlong i endIPlong i temp long2ip i. this is a total hack there must be a better way thisQuad explode temp if thisQuad 3 0 thisQuad 3 255 ip k temp. return ip CalculateIPRange. get the first ip and last ip from cidr network id and mask length i will integrate this function into Rong Framework author param string cidr 56 15 0 6 16 network id mask length return array ipArray array 0 first ip of the network , 1 last ip of the network Each element of ipArray s type is long int, use long2ip ipArray 0 to convert it into ip string example list longstartIp longendIp getIpRange 56 15 0 6 16 echo start ip long2ip longstartIp echo br echo end ip long2ip longendIp. function getIpRang cidr. list ip mask explode cidr. maskBinStr strrepeat 1 mask strrepeat 0 32 - mask net mask binary string inverseMaskBinStr strrepeat 0 mask strrepeat 1 32 - mask inverse mask. ipLong ip2long ip ipMaskLong bindec maskBinStr inverseIpMaskLong bindec inverseMaskBinStr netWork ipLong ipMaskLong. start netWork 1,ignore network ID eg 192 168 1 0. end netWork inverseIpMaskLong - 1 ignore brocast IP eg 192 168 1 255 return array start end. I would just like to try and clear up simply that if storing IPV4 addresses in an SQL database you should use an unsigned int 4 bytes. The easiest way to do this in PHP is to use sprintf. php dottedFormatAddress 127 0 0 1 ipv4address sprintf u ip2long dottedFormatAddress. Primary reasons are it s compatible with database functions like MySQL s INETATON INETNTOA which also use unsigned int s , it s efficient, and it s the most common format used by IP lookup databases. Be aware when you re running 64bit system, ip2long will result 64 bit integer which doesn t fit in MySQL INT, you can use BIGINT or INT UNSIGNED because on 64bit systems ip2long will never return negative integer See also. I ve write an IPFilter class to check if a ip is in given ips. php class IPFilter private static IPTYPESINGLE single private static IPTYPEWILDCARD wildcard private static IPTYPEMASK mask private static IPTYPESECTION section private allowedips array. public function construct allowedips this - allowedips allowedips. public function check ip allowedips null allowedips allowedips allowedips this - allowedips. foreach allowedips as allowedip type this - judgeiptype allowedip subrst calluserfunc array this subchecker type , allowedip ip. private function judgeiptype ip if strpos ip return self IPTYPEWILDCARD. if strpos ip return self IPTYPEMASK. if strpos ip - return self IPTYPESECTION. if ip2long ip return self IPTYPESINGLE. private function subcheckersingle allowedip ip return ip2long allowedip ip2long ip. private function subcheckerwildcard allowedip ip allowediparr explode allowedip iparr explode ip for i 0 i count allowediparr i if allowediparr i return true else if false allowediparr i iparr i return false. private function subcheckermask allowed ip ip list allowedipip allowedipmask explode allowedip begin ip2long allowedipip ip2long allowedipmask 1 end ip2long allowedipip. ip2long allowedipmask 1 ip ip2long ip return ip begin ip end. private function subcheckersection allowedip ip list begin end explode - allowedip begin ip2long begin end ip2long end ip ip2long ip return ip begin ip end. In using a combination of jbothe s code below and some of the mask 0xFFFFFFFF 32 - bits type code, I ran into an error with some later calculations on a 64 bit machine. Keep in mind that when you re analyzing numbers meant to be treated as 32 bits wide such as IP addresses , you may want to truncate them Without relying on other libraries, it was simple enough to follow any calculations that may end with different results on a 64 bit machine with 0xFFFFFFFF. Though in many cases, it seems like it might be simpler to just use.0 for initial shifting to create the network mask instead of 0xFFFFFFFF I don t know that it guarantees further opera tions to work as expected though. samb057 at gmail dot com. This function will not return a correct bigint. baseconvert is limited to the double type, which usually counts 64bits and not 128 like an IPv6 address. will NOT be converted to 128 2 -1.You should use a bigint lib s multiplication function, with decimal shifting factors defined as string constants much faster than recalculating them every time Grab 8 short integers the 16bits between the with baseconvert hex,16,10 and shift the 7 higher ones with a bigintmultiplication. Of course you can also do it with less bigint ops using 32bit integers, but then you should create them this way additionally sprintf for making an uint32 string uint32 sprintf u, intval baseconvert hex,16,10.Finally, bigintadd the shifted ones to the least unshifted significant interger string and be happy. PS I m working on an IPv4 6 tool class with raw also endianness , 6 4 compatibility and validation methods, I ll post it here as soon as it s finished and tested. I wrote a small function to val idate a netmask We have a form where the netmask of a given server is entered in, and I wanted to make sure it was valid Hope this is useful. php Netmask Validator function checkNetmask ip if ip2long ip return false elseif strlen decbin ip2long ip 32 ip2long ip 0 return false elseif ereg 01 decbin ip2long ip ereg 0 decbin ip2long ip return false else return true. Here s a simple IP address match checking function. It takes 3 arguments ip address to check after ip2long , ip address to check against after ip2long , and mask to check against integer 0-32.Just make sure you perform ip2long on the ip addresses before inputting them to the function. php function matchip checkip matchip matchmask 32 for i 0 i matchmask i n pow 2 31 - i if n checkip n matchip return FALSE. return TRUE. I ve been looking for a function like this for a while, i hope it helps someone. Below is a merged form of all various notes, and a better and correct network matching function. function netmatch network ip determines if a network in the form of 192 168 17 1 16 or 127 0 0 1 255 255 255 255 or 10 0 0 1 matches a given ip iparr explode network networklong ip2long iparr 0. x ip2long iparr 1 mask long2ip x iparr 1 x 0xffffffff 32 - iparr 1 iplong ip2long ip. echo iparr 1 return iplong mask networklong mask. echo netmatch 192 168 17 1 16 192 168 15 1 n returns true echo netmatch 127 0 0 1 255 255 255 255 127 0 0 2 n returns false echo netmatch 10 0 0 1 10 0 0 1 n returns true. Note ip2long and long2ip do not function as the c linux functions inetaddr and inetntoa They store the long in reverse byte order little endian vs big endian i guess For example you send 10 0 0 1 to inetntoa you take the long from the result and you pass it to long2ip you get 1 0 0 10 You won t run into this issue unless you use a database both from c linux programs and php scripts. My first idea was to reverse the long, but unfortunatley the long was stored as unsigned and i got a lot of problems doing calculations with it some operations would work well others not probably it was stored as float i do not know for sure. So my solution was. php function strrevip str ar explode str return ar 3 ar 2 ar 1 ar 0.and i take the result from inetntoa and parse it as strrevip long2ip var. a little function to make a range in this form 0 0 0 1 0 0 0 255 0 0 0 1 255 0 0 0 1 255 255 255 255 0 0 0 1 255 255 255 255. php primo 62 4 32 0 ultimo 62 4 63 255 echo dorange primo ultimo Example. function dorange primo ultimo list a b c d explode primo list e f g h explode ultimo if a e return primo ultimo else if b f return primo f g h else if c g return primo g h else if d h return primo h else return - 1 error Please write me if you have any suggestion. Here are my versions of prefix to mask and mask to prefix conversions You can remove first lines with if preg of each function if you don t want sanity precheck. function prefix2Mask prefix if pregmatch 0 0-2 0-9 3 0-2 , prefix return false wrong prefix return long2ip 0xffffffff 32 - prefix. function mask2Prefix mask if pregmatch 0-1 0-9 0-9 2 0-4 0-9 25 0-5 0-9 0-9 0-9 0-1 0-9 0-9 2 0-4 0-9 25 0-5 0-9 0-9 0-9 , mask return false wrong mask m2p strpad substr decbin ip2long mask , -32, 32 , 32, 0 , STRPADLEFT if pregmatch 1 0 , m2p, m return false wrong mask return strlen m 1.I re-wrote the functions from jbothe at hotmail dot com as a little exercise in OO and added a couple of extra functions. -------------- Create new class function ipv4 address netbits this - address address this - netbits netbits. -------------- Return the netmask function netmask return long2ip ip2long 255 255 255 255 32 - this - netbits. -------------- Return the network that the address sits in function network return long2ip ip2long this - address ip2long this - netmask. -------------- Return the broadcast that the address sits in function broadcast return long2ip ip2long this - network. ip2long this - netmask. -------------- Return the inverse mask of the netmask function inverse return long2ip. ip2long 255 255 255 255 32 - this - netbits. ip new ipv4 192 168 2 1 24 print Address ip - address n print Netbits ip - netbits n print Netmask ip - netmask n print Inverse ip - inverse n print Network ip - network n print Broadcast ip - broadcast n. A common way to express IP addresses and subnet masks is to use what is refered to as slash notation Instead of writing out IP 192 168 100 2 Subnet Mask 255 255 240 0 Writing out 192 168 100 2 20 is much shorter. If you are looking for a way to convert a subnet mask into it s slash notation counterpart, here is a single line of code that can perform this task. php slashnotation strlen pregreplace 0 decbin ip2long subnetmask. For example A subnet mask of 255 255 240 0 expressed in binary looks like this 11111111111111111111000000000000 This gives us a slash notation of 20 which is simply counting the number of 1 s in the masks binary representation. Here is a function that uses this code to return an IP address and subnet mask in slash notation. php function slashnotation ip mask return ip strlen pregreplace 0 decbin ip2long mask. calling slashnotation 192 168 100 2 , 255 255 255 0 will return 192 168 100 2 24.Hope this is of use to some of you out there. Just to save you some time. Beware that octets in IP address are being treated as numbers So, 10 0 0 11 is not equal to 10 0 0 011 011 is octal number base 8 , so it converts to 9 You can even go further and see that 10 0 0 0xa also works equals to 10 0 0 16.This is not PHP issue, though. Here is a modified version of the code posted by legetz81 AT yahoo dot com It handles the shorter, and more common, notation 189 128 11. ipaddrcidr 192 168 37 215 27 cidr ipaddrcidr. function cidr ipaddrcidr. iparr explode ipaddrcidr. dotcount substrcount iparr 0 , padding strrepeat 0 3 - dotcount iparr 0 padding. bin for i 1 i 32 i bin iparr 1 i 1 0 iparr 1 bindec bin. ip ip2long iparr 0 nm ip2long iparr 1 nw ip nm bc nw. echo Number of Hosts bc - nw - 1 n echo Host Range long2ip nw 1 - long2ip bc - 1 n. This will produce Number of Hosts 30 Host Range 192 168 37 193 - 192 168 37 222.The following script will print out subnet statistics when you supply the IP Address and Subnet Mask Usefull to calculate the broadcast address and network address as well as the number of hosts and the range of IP addresses in the subnet. usr local bin php php ipaddr 172 14 1 57 subnetmask 255 255 255 0. ip ip2long ipaddr nm ip2long subnetmask nw ip nm bc nw. echo IP Address long2ip ip n echo Subnet Mask long2ip nm n echo Network Address long2ip nw n echo Broadcast Address long2ip bc n echo Number of Hosts bc - nw - 1 n echo Host Range long2ip nw 1 - long2ip bc - 1 n. Produces the output. IP Address 172 14 1 57 Subnet Mask 255 255 255 0 Network Address 172 14 1 0 Broadcast Address 172 14 1 255 Number of Hosts 254 Host Range 172 14 1 1 - 172 14 1 254.If you want to get the interface of an IP, based on the local route table, use this. php function GetIfaceforIP userip route bin netstat - rn. exec route aoutput foreach aoutput as key line if key 1 line eregreplace space , line list network gateway mask flags mss window irtt iface explode , line if ip2long userip ip2long mask ip2long network return iface. A quick way to find which IP address belong to which network without even creating a single PHP function pure SQL. Scenario - I have one table that has a list of host ip addresses - I have another table that list all the networks addresses - I need to find which host belongs to which network. Solution 1 - with PHP Long 1 create a PHP function that will calculate and compare IP address with the network 2 extract data from the table nodes, calculate the IP with its mask using a PHP function to get the network address 3 do the same with table network1 4 compare result 2 and result 3 once finished put them into an array to be presented as an HTML 5 done. Solution 2 - With SQL Very Very Fast Short 1 create sql with inetaton f unction table joins 2 extract the data from sql outputs 3 done. how SQL select as hostname, as hostip, as netname from nodes a, network1 b where. Hope this helps. Thanks to sealbreaker for the conversion method I d seen php ip2long ip 0x7FFFFFFF 0x80000000 before, but noticed it didn t work on all ips You ve discovered why. In case anyone is wondering what sealbreaker means by obtaining an integer value , s he means an unsigned int, vs the signed version ip2long provides Well, technically this conversion will sometimes give you a float since php s integer type is signed. The good news is that long2ip will correctly handle converting these signed versions back into ips. So, to get an unsigned version of an ip ie, always 0. may return a php int or float signed substr ip 0 3 127 ip2long ip 0x7FFFFFFF 0x80000000 ip2long ip. will return a string version signed2 sprintf u ip2long ip. vardump signed signed2 long2ip signed , long2ip signed2.P S If you re storing IPs in MySQL, there is NO POINT in converting to these unsigned values to place in an INT UNSIGNED column Just use an INT SIGNED column, and directly use the result from ip2long The only reason you should really need to force your ip2long result into its unsigned version is if you need to compare them with another source that uses unsigned ie some IP database lookup utils use unsigned. As a note if you are using PHP 4, PHP 5 and are looking to get the integer value of an IP address, i have found that the following works flawlessly for converting to and from IPv4 and it s integer equivalent I must give credit elsewhere for this portion of the code ip2long ip 0x7FFFFFFF 0x80000000 I looked but was unable to find the comment where it was included. ip 127 0 0 0 as an example. integerip substr ip, 0, 3 127 ip2long ip 0x7FFFFFFF 0x80000000 ip2long ip. echo integerip integer value of IP address echo long2ip integerip convert to an IPv4 formatted address ----------------------- Results are as follows ----------------------- 2130706432 127 0 0 0 ----------------------- 255 255 255 255 converts to 4294967295 and back to 255 255 255 255 209 65 0 0 converts to 3510697984 and back to 209 65 0 0 12 0 0 0 converts to 201326592 and back to 12 0 0 0 1 0 0 0 converts to 16777216 and back to 1 0 0 0.NOTE ip2long should NOT be used for CIDR calculation Instead, you should use something like the following. php get the base and the bits from the ban in the database list base bits explode CIDR. now split it up into it s classes list a b c d explode base. now do some bit shfiting switching to convert to ints i a 24 b 16 c 8 d mask bits 0 0. here s our lowest int low i mask. here s our highest int high i. mask 0xFFFFFFFF. now split the ip were checking against up into classes list a b c d explode iptocheck. now convert the ip we re checking against to an int check a 24 b 16 c 8 d. if the ip is within the range, including highest lowest values, then it s witin the CIDR range if check low check high return 1 else return 0.This means that you should check to see if the IP address is of the correct format each time. I made one tiny change to Stephane s routine below when I had problems with spaces in an IP range I moved the trim function before the ip2long call. php function netMatch network ip. network trim network ip trim ip. d strpos network - if d false iparr explode network. if pregmatch d d d d iparr 0 , matches iparr 0 0 Alternate form 194 1 4 24. networklong ip2long iparr 0 x ip2long iparr 1. mask long2ip x iparr 1 x 0xffffffff 32 - iparr 1 iplong ip2long ip. return iplong mask networklong mask else from ip2long trim substr network 0 d to ip2long trim substr network d 1. ip ip2long ip return ip from and ip to. A quick and efficient way to compare two IPs with a given mask. php function ipmatch ip1 ip2 mask if ip2long ip1. pow 2 32 - mask - 1 ip2long ip2. pow 2 32 - mask - 1 return true else return false. Here s an application of it that selects the best IP given the choice of a possibly private or invalid forwarded address or a possibly proxy apparent address. php a SERVER if a ipmatch a 10 0 0 0 8 ipmatch a 172 16 0 0 12 ipmatch a 192 168 0 0 16 ipmatch a 255 255 255 255 32 ip SERVER REMOTEADDR else ip a. Or use it to ban people. php bannedip 135 23 12 3 if ipmatch ip bannedip 32 die BANNED. The bitwise comparison the function uses can be done in SQL to do ban matches right in your database. Here is a function that tells you if an ip address is in a CIDR range However, the CIDR argument can be an array of CIDRs This was created from other matchCIDR functions in the user notes. php function matchCIDR addr cidr. addr should be an ip address in the format 0 0 0 0 cidr should be a string in the format 100 8 or an array where each element is in the above format. if isarray cidr. foreach cidr as cidrlet if matchCIDR addr cidrlet output true. list ip mask explode cidr. mask 0xffffffff 32 - mask. output ip2long addr mask ip2long ip mask. return output. For PHP5 I had to replace masklong pow 2,32 - pow 2, 32- iparr 1. masklong 0xffffffff 32 - iparr 1.in dzver s IPMatch Function below. Mix of rbsmith s function and pasted above url. php returns 1 if ip is part of network. function IPMatch network ip iparr explode network networklong ip2long iparr 0. masklong pow 2 32 - pow 2 , 32 - iparr 1 iplong ip2long ip. if iplong masklong networklong return 1 else return 0. network 200 100 50 0 23 ip 200 100 51 55 ip2 200 100 52 2.echo IPMatch network ip prints 1 echo IPMatch network ip2 prints 0.Yet another word on IPMatch here is the complete functions as described by php-net at dreams4net dot com on 08-Aug-2002 09 31. php determine if an IP address is within a particular network with mask function IPMatch network mask ip iplong ip2long ip networklong ip2long network masklong ip2long mask. if iplong masklong networklong return true else return false. Thank you, it is simple, fast, and best of all works. I ve maded simple script that allow you filter traffic by networks, like if you want to deny 192 168 0 0 24.I used ncritten s myip2long function for this. Sorry for such non-optimized code, but it works enough good. file 192 168 0 0 24 172 16 0 0 16 10 0 0 0 8. php ncritten s function myip2long. function myip2long ip if isnumeric ip return sprintf u floatval ip else return sprintf u floatval ip2long ip. function to chek ip if it in one of denyied allowed networks. function ipfilter ip match 0. converting ip address in binary ipaddr decbin myip2long ip. the file wich contains allowed denyied networks if fopen r source file. foreach source as line. exploding each network to obtaid network address and cidr network explode line netaddr decbin myip2long network 0 cidr network 1. and finaly cheking quantity of network bits from left to right wich is equal to cidr is equal to the same bits of ip address if substr netaddr 0 cidr substr ipaddr 0 cidr match 1 break return match. this function will return 1 if IP match to some network or 0 if will not match. and finaly the chek will be like this. userip SERVER REMOTEADDR. if ipfilter userip 1 echo allowed else echo deny. P S Sorry for my bad english. Here is a script that will calculate host range and number of hosts with a given ip address CIDR notation modified code which was posted by phl AT. php ipaddrcidr 192 168 37 215 27 iparr explode ipaddrcidr. bin for i 1 i 32 i bin iparr 1 i 1 0 iparr 1 bindec bin. ip ip2long iparr 0 nm ip2long iparr 1 nw ip nm bc nw. echo Number of Hosts bc - nw - 1 n echo Host Range long2ip nw 1 - long2ip bc - 1 n. This will produce Number of Hosts 30 Host Range 192 168 37 193 - 192 168 37 222. php Check if given mask is correct You can check the short format mask like 8,16,24 or long format like 255 255 255 0.function isIpMask mask. format if pregmatch 0-9 0-9 0-9 0-9 mask format long else if mask 30 format short else return false switch format case long mask decbin ip2long mask break case short tmp mask for i 0 i mask i tmp 1 for j 0 j 32 - mask j tmp 0 mask tmp break if strlen mask 32 for i 0 i 32 i bit substr mask i 1 if bit - substr mask i 1 1 0 return false return true EXAMPLE isIpMask 255 255 255 0 - return true isIpMask 24 - return true isIpMask 5 5 5 5 - return false. EDIT BY danbrown AT php DOT net Contains a fix provided by greg AT netops DOT gvtc DOT com on 19-Dec-2005.Just a little function to check visitor s ip if it is in given range or not I couldn t find anywhere so i improvise. php function iniprange ipone iptwo false if iptwo false if ipone SERVER REMOTEADDR ip true else ip false else if ip2long ipone ip2long SERVER REMOTEADDR ip2long iptwo ip2long SERVER REMOTEADDR ip true else ip false return ip usage echo iniprange 192 168 0 0 192 168 1 254.A simple function to compare two IP addresses against a netmask Useful if you re locking down a web app with an IP address, but can t force the IPs to be exactly the same. php function ipcompare ip1 ip2 mask masked1 ip2long ip1 ip2long mask bitwise AND of ip1 with the mask masked2 ip2long ip2 ip2long mask bitwise AND of ip2 with the mask if masked1 masked2 return true else return false. php ipcompare 192 168 1 63 192 168 1 65 255 255 255 0 true ipcompare 192 168 1 63 192 168 1 65 255 255 255 192 false.

No comments:

Post a Comment