Saturday 3 March 2018

244 바이너리 옵션으로 변환


이진 - 이진 문자열에서 필드를 삽입하고 추출합니다. 이 명령은 이진 데이터를 조작 할 수있는 기능을 제공합니다. 하위 명령 이진 형식은 일반 Tcl 값에서 이진 문자열을 만듭니다. 예를 들어 32 비트 아키텍처에서는 값 16 및 22가 주어지면 두 개의 4 바이트 정수로 구성된 8 바이트 2 진 문자열, 각 숫자에 하나씩 부속 명령 2 진 스캔은 2 진 문자열에서 데이터를 추출하여이를 일반 Tcl 문자열 값으로 리턴합니다. 2 진 코드 및 2 진 디코드 부속 명령 convert 바이너리 데이터를 MIME 메시지에 사용되는 base64와 같은 문자열 인코딩에 또는 문자열 인코딩에서 가져올 수 있습니다. 이진 데이터를 읽을 수있는 문자열로 인코딩하면 시작 바이너리 데이터가 사용할 인코딩의 이름 및 인코딩과 함께 바이너리 인코딩 명령에 전달됩니다 원하는 특정 옵션 인코딩 된 데이터는 바이너리 디코드를 사용하여 다시 바이너리 형식으로 변환 할 수 있습니다. 다음 형식과 옵션이 지원됩니다. base64 base64 바이너리 enco ding은 메일 메시지 및 XML 문서에서 일반적으로 사용되며 대 / 소문자와 숫자를 주로 사용합니다. 정보를 잃지 않고 임의로 다시 래핑 할 수 있다는 점이 다릅니다. 인코딩하는 동안 다음 옵션이 지원됩니다. - maxlen 길이 출력은 길이 문자를 초과하지 않는 줄로 분리되어야합니다. 기본적으로 줄은 분할되지 않습니다. - wrapchar character - maxlen 옵션으로 인해 줄이 분리 될 때 문자를 사용하여 줄을 구분해야 함을 나타냅니다. 기본적으로 이것은 a입니다. 개행 문자. n. 해독 중에 다음 옵션이 지원됩니다.-strict 공백 문자를 만났을 때 오류가 발생하도록 지시합니다. 그렇지 않으면 16 진수를 무시합니다. 16 진수 2 진수 인코딩은 각 바이트를 빅 엔디안의 한 쌍의 16 진수로 변환합니다 인코딩 중에는 옵션이 지원되지 않습니다. 디코딩하는 동안 다음 옵션이 지원됩니다.-strict 공백을 발견하면 디코더에 오류가 발생하도록 지시합니다 문자 그렇지 않으면 그것을 무시합니다. uuencode Unix 시스템과 USENET간에 데이터를 전송하는 데 일반적으로 사용되는 Uuencode 이진 인코딩은 요즘은 덜 일반적이지만 base64 이진 인코딩으로 대체되었습니다. 인코딩하는 동안 다음 옵션이 지원됩니다. maxlen length 출력을 길이 문자보다 큰 행으로 분리해야 함을 나타냅니다. 기본적으로 행은 분할되지 않습니다. - wrapchar character - maxlen 옵션으로 인해 행이 분할 될 때 문자를 사용하여 행을 분리해야 함을 나타냅니다 기본적으로 이것은 개행 문자 n입니다. 디코딩 중에는 다음 옵션이 지원됩니다.-strict 공백 문자를 만나는 경우 오류를 발생하도록 디코더에 지시합니다. 그렇지 않으면 무시합니다. 이진 형식 명령은 레이아웃이 formatString에 의해 지정되어 그 내용이 추가의 인수로부터 나온다 결과의 바이너리 치가 돌려 주어집니다. formatString는, 0 개 이상의 필드 지정자가 0 개 이상의 공백으로 구분 된 경우 각 필드 지정자는 하나의 문자 유형 다음에 선택적 플래그 문자 다음에 옵션 숫자 숫자가옵니다. 대부분의 필드 지정자는 형식화 할 값을 얻기 위해 하나의 인수를 사용합니다. 값은 형식화 될 것입니다. 일반적으로 값은 지정된 유형의 항목이 값에서 가져온 항목 수를 나타냅니다. 존재하는 경우, 카운트는 음수가 아닌 10 진 정수이거나 일반적으로 값의 모든 항목이 사용됨을 나타냅니다 인수의 수가 인수를 사용하는 형식 문자열의 필드 수와 일치하지 않으면 오류가 생성됩니다. 이진 형식에 대해서는 플래그 문자가 무시됩니다. 여기에는 필드 지정자와 인수 사이의 관계를 명확히하는 작은 예제가 있습니다 첫 번째 인수는 네 개의 숫자 목록이지만 관련 필드 지정자에 대한 개수가 3이므로 처음 세 개만 사용됩니다 두 번째 인수 nt는 두 번째 필드 지정자와 연관됩니다. 결과 바이너리 문자열은 4 개의 숫자 1 0, 2 0, 3 0 및 0을 포함합니다. 각 유형 카운트 쌍은 이진 데이터를 통해 가상 커서를 이동하여 현재 위치에 바이트를 저장하고 진행합니다 커서는 처음에 저장된 마지막 바이트 바로 다음에 있습니다. 커서는 처음에는 데이터의 시작 부분에 위치 0에 있습니다. 유형은 다음 문자 중 하나 일 수 있습니다. a 출력 문자열에 길이가 count 인 바이트 문자열을 저장합니다. 모든 문자는 modulo 256 즉, 모든 문자의 하위 바이트가 사용되고 상위 바이트가 삭제되므로 u0000 - u00ff 문자를 사용하여 완전히 표현할 수없는 문자열을 저장할 때 먼저 인코딩 변환 명령을 사용하여 문자열을 외부 표현으로 변경해야합니다. 문자가 ISO 8859-1 문자 세트의 일부가 아닌 경우 truncation이 바람직하지 않습니다. arg가 count 바이트보다 작은 경우, 0 바이트를 추가로 사용하여 필드를 채 웁니다. arg가 th보다 길면 지정된 길이를 초과하면 추가 문자는 무시됩니다. count가 0이면 모든 바이트가 형식화됩니다 count가 생략되면 한 문자가 형식화됩니다. 예를 들어 알파에 해당하는 문자열을 반환합니다 000 000bravoc. will 문자열은 342 202 254에 해당하며 유로 통화 문자의 경우 UTF-8 바이트 시퀀스이고 244는 유로 통화 문자의 ISO 8859-15 바이트 시퀀스와 같은 문자열을 반환합니다. 이것은 문자의 상위 비트를 잘라 냄으로써 254 ie xac에 해당하는 문자열을 반환하며, 이는 아마도 원하는 것이 아닙니다. 이 형식은 공백이 null 대신 패딩에 사용된다는 점을 제외하면 a와 동일합니다. 예를 들어. will return alpha bravoc. b 출력 문자열의 각 바이트 내에서 카운트 2 진수 문자열을 낮은 순서에서 높은 순서로 저장합니다. Arg는 1 및 0 문자의 순서를 포함해야합니다. 결과 바이트는 첫 번째 순서에서 마지막 순서로 내보내집니다. 저가에서 높은 형식으로 서식이 지정됩니다. h 각 바이트 내에서의 순서 arg가 카운트 자리보다 적은 경우 나머지 비트에 0이 사용됩니다. arg가 지정된 자릿수 이상인 경우 추가 숫자는 무시됩니다. count가 0이면 arg의 모든 숫자는 형식이 지정되면 count가 생략되면 한 자리가 형식화됩니다. 형식화 된 비트 수가 바이트 경계에서 끝나지 않으면 마지막 바이트의 나머지 비트는 0이됩니다. 예를 들어 x07 x87 x05와 같은 문자열을 반환합니다. B이 형식은 비트가 각 바이트 내에서 하이 - 로우 순서로 저장된다는 점을 제외하면 b와 동일합니다. 예를 들어, xe0 xe1 xa0에 해당하는 문자열을 반환합니다. H 16 진수의 카운트 문자열을 상위 - 출력 문자열의 각 바이트 내에서 낮은 값 Arg은 집합에 일련의 문자를 포함해야합니다. 0123456789abcdefABCDEF 결과 바이트는 첫 번째 순서에서 마지막 순서로 내보내집니다. 각 바이트 내에서 16 진수가 높은 순서에서 낮은 순서로 형식이 지정됩니다. 자릿수를 계수하면 0이됩니다. 나머지 숫자에 대해 sed arg가 지정된 자릿수보다 많은 경우 추가 숫자는 무시됩니다 count가 0이면 arg의 모든 숫자가 형식화됩니다 count가 생략되면 한 자리가 형식화됩니다 형식이 지정된 바이트가 바이트 경계에서 끝나지 않으면 마지막 바이트의 나머지 비트는 0이됩니다. 예를 들어 xab x00 xde xf0 x98.h와 같은 문자열을 반환합니다. 이 형식은 숫자가 각 바이트 내에서 low-to-high 순서입니다. 거의 필요 없습니다. 예를 들어, xba에 해당하는 문자열을 반환합니다. x00 xed x0f x89.c 출력 문자열에 하나 이상의 8 비트 정수 값을 저장합니다. 개수가 지정되지 않으면 arg 정수 값으로 구성되어야 함 count가 지정되면 arg는 적어도 그 많은 정수를 포함하는 목록으로 구성되어야합니다 각 정수의 하위 8 비트는 커서 위치에 1 바이트 값으로 저장됩니다 count가 리스트의 정수는 포맷된다. elem의 수 목록의 ents가 count보다 크면 추가 요소가 무시됩니다. 예를 들어 x03 xfd x80 x04 x02 x05에 해당하는 문자열을 반환합니다. 반면 error. s를 생성합니다. 이 형식은 c와 동일하지만 하나 또는 출력 문자열에서 리틀 엔디안 바이트 순서로 더 많은 16 비트 정수 각 정수의 하위 16 비트는 커서 위치에 2 바이트 값으로 저장되며 최하위 바이트가 먼저 저장됩니다. 예를 들어 다음과 같습니다. a를 반환합니다. 문자열은 x03 x00 xfd xff x02 x01.S와 같습니다. 출력 문자열에 빅 엔디안 바이트 순서로 하나 이상의 16 비트 정수를 저장한다는 점을 제외하면이 형식은 s와 같습니다. 예를 들어 x00 x03에 해당하는 문자열을 반환합니다. xff xfd x01 x02.t이 형식은 s 및 S와 동일 합니다만, 출력 문자열에 16 비트 정수를 Tcl 스크립트가 실행중인 시스템의 기본 바이트 순서로 저장한다는 점만 다릅니다. 기본 바이트 기계의 순서는 tclpla의 byteOrder 요소를 참조하십시오. tform 배열 i이 형식은 출력 문자열에 리틀 엔디안 바이트 순서로 하나 이상의 32 비트 정수를 저장한다는 점을 제외하면 c와 동일합니다. 각 정수의 하위 32 비트는 4 바이트 값으로 저장됩니다. 처음에 최하위 바이트가 저장된 커서 위치 예를 들어 x03에 해당하는 문자열을 반환합니다. x00 x00 x00 xfd xff xff xff x00 x00 x01 x00.I이 형식은 하나 이상의 하나 이상의 출력 문자열에서 빅 엔디안 바이트 순서로 32 비트 정수 예를 들어, x00 x00 x00 x03 xff xff xff xfd x00 x01 x00 x00.n과 같은 문자열을 반환합니다. 이 양식은 숫자와 일반이 i와 I가 같습니다. Tcl 스크립트가 실행중인 컴퓨터의 기본 바이트 순서로 출력 문자열에 32 비트 정수를 저장한다는 점을 제외하고는 컴퓨터의 기본 바이트 순서를 확인하려면 tclplatform 배열의 byteOrder 요소를 참조하십시오. 양식은 하나 이상의 64 비트 정수 i를 저장한다는 점을 제외하고는 c와 동일합니다. 출력 문자열에서 n little-endian 바이트 순서 각 정수의 하위 64 비트는 커서 위치에 8 바이트 값으로 저장되고 최하위 바이트가 먼저 저장됩니다. 예를 들어 HelloTcl. W 문자열을 반환합니다. 양식은 출력 문자열에 big-endian 바이트 순서로 하나 이상의 64 비트 정수를 하나 이상 저장한다는 점을 제외하면 w와 동일합니다. 예를 들어 문자열 BigEndian. m을 반환합니다. 이 양식은 일반적으로 w의 미러가 동일합니다 w와 W를 제외하고는 출력 문자열에 64 비트 정수를 Tcl 스크립트가 실행되는 컴퓨터의 기본 바이트 순서로 저장합니다. 컴퓨터의 기본 바이트 순서를 확인하려면 해당 바이트의 byteOrder 요소를 참조하십시오. tclplatform 배열 f이 형식은 출력 문자열에서 기계 고유 표현으로 하나 이상의 단 정밀도 부동 소수점 숫자를 하나 이상 저장한다는 점을 제외하고는 c와 동일합니다. 이 표현은 아키텍처 전반에서 이식 가능하지 않으므로 사용하면 안됩니다 의사 소통하기 부동 소수점 수는 아키텍처에 따라 다를 수 있으므로 생성되는 바이트 수가 다를 수 있습니다. 값이 시스템의 원래 표현을 오버플로하면 시스템에서 정의한 FLTMAX의 값은 다음과 같이됩니다. 대신 Tcl이 내부에서 배정도 부동 소수점 숫자를 사용하기 때문에 단 정밀도로 변환 할 때 약간의 정밀도가 손실 될 수 있습니다. 예를 들어 Intel Pentium 프로세서에서 실행되는 Windows 시스템에서 xcd xcc xcc와 같은 문자열을 반환합니다. x3f x9a x99 x59 x40.r이 형식은 리얼 엔디안 순서로 단 정밀도 부동 소수점 숫자를 저장한다는 점을 제외하고는 f와 같습니다. 이 변환은 IEEE 부동 소수점 표현을 사용하는 시스템에서 사용할 때만 의미있는 출력을 생성합니다 일반적이지만 보편적이지는 않습니다. R이 형식은 단 정밀도 부동 소수점 숫자를 빅 엔디안 순서로 저장한다는 점을 제외하면 r과 같습니다. d이 형식은 다음과 같습니다. f를 제외하고는 하나 이상의 배정 밀도 부동 소수점 숫자를 출력 문자열에 기계 고유 표현으로 저장합니다. 예를 들어, Intel Pentium 프로세서에서 실행되는 Windows 시스템에서 x9a x99 x99와 같은 문자열을 반환합니다. x99 x99 x99 xf9 x3f. q이 형식은 동적으로 d의 미러는 d와 같지만 리니어 엔디안 순서로 배정 밀도 부동 소수점 수를 저장합니다. 이 변환은 IEEE 부동 소수점을 사용하는 시스템에서 사용할 때만 의미있는 출력을 생성합니다 point 표현은 매우 보편적이지 만 보편적이지는 않다. Q이 형식은 q와 동일하지만 빅 엔디 언 순서로 배정 밀도 부동 소수점 수를 저장한다. x 출력 문자열에 널 바이트 수를 저장한다. count가 지정되지 않으면 하나의 널 바이트 count가 오류를 생성하면이 유형은 인수를 사용하지 않습니다. 예를 들어 abc와 같은 문자열을 반환합니다. 000def 000 000ghi. X 출력 문자열에서 커서를 뒤로 이동합니다. count i s 또는 현재 커서 위치보다 큰 경우 커서는 위치 0에 배치되어 다음 저장된 바이트가 결과 문자열의 첫 번째 바이트가됩니다 count가 생략 된 경우 커서는 1 바이트 뒤로 이동됩니다. 이 유형은 소비하지 않습니다 argument for example. will return dghi. count로 지정된 출력 문자열의 절대 위치로 커서를 이동합니다. Position 0은 출력 문자열의 첫 번째 바이트를 나타냅니다. count가 지금까지 저장된 마지막 바이트를 초과하는 위치를 참조하면 null 바이트가 초기화되지 않은 위치에 배치되고 커서가 지정된 위치에 배치됩니다. count가이면 커서는 출력 문자열의 현재 끝으로 이동됩니다. count가 생략되면 오류가 생성됩니다. 이 유형은 인수를 사용하지 않습니다. 예를 들어 abfdeghi를 반환합니다. 000 바이너리 스캔 명령은 바이너리 문자열의 필드를 구문 분석하여 수행되는 변환 수를 반환합니다. 문자열은 구문 분석 할 입력 바이트를 문자 당 한 바이트 씩주고 바이트로 표현할 수없는 문자는 상위 비트를 잘게 잘라낸 다음 formatString은 구문 분석 방법을 나타냅니다. 각 varName은 문자열에서 필드를 스캔 할 때 변수의 이름을 제공합니다. 결과는 해당 변수에 할당됩니다. 이진 형식과 마찬가지로 formatString은 다음과 같습니다. 0 개 이상의 공백으로 구분 된 일련의 0 개 이상의 필드 지정자 각 필드 지정자는 단일 문자 다음에 선택적 플래그 숫자 다음에 선택적 숫자 숫자가옵니다. 대부분의 필드 지정자는 스캔 된 값이 들어갈 변수를 얻기 위해 하나의 인수를 사용합니다 이진 데이터를 해석하는 방법을 문자 유형으로 지정합니다. 일반적으로 데이터에서 지정된 유형의 항목 수를 나타냅니다. 존재하는 경우, 카운트는 음수가 아닌 10 진수이거나 일반적으로 데이터의 나머지 항목이 사용됩니다. 현재 필드 위치 지정자를 충족시키기 위해 현재 커서 위치 이후에 충분한 바이트가 남아 있지 않으면 해당 변수가 그대로 유지되고 설정된 변수 수와 함께 즉시 바이너리 스캔이 반환됩니다. If 인수를 소비하는 형식 문자열의 모든 필드에 대해 충분한 인수가 없으면 오류가 생성됩니다. 플래그 cha racter u는 어떤 타입을 부호없는 값으로 읽게 할 수 있습니다. 플래그는 모든 필드 타입에 대해 허용되지만 비 - 정수 필드에서는 무시됩니다. 바이너리 포맷과 비슷한 예제는 필드 지정자와 인수 사이의 관계를 설명해야합니다 이 명령은 변수 바이트에 2 진 문자열을 제공하고 3 번째 정수 목록을 먼저 변수에 할당하고 변수 2에 하나의 값을 할당합니다. 바이트에 8 바이트 미만이 포함되면 즉 4 바이트 2 바이트 2 바이트에 6 바이트 이하의 3 바이트 정수가 포함되어 있다면, 처음에는 아무 것도 할당되지 않을 것입니다. 그러므로 변수는 이전에 설정되지 않았다고 가정하여 인쇄 할 것입니다. cs 및 S 및 64 비트 시스템의 i 및 I는 긴 데이터 크기 값으로 스캔됩니다. 이렇게하면 높은 비트가 문자 0x80, 단락 0x8000, int의 0x80000000으로 설정된 값이 부호 확장됩니다. 따라서 서명되지 않은 값이 필요한 경우 u 플래그 문자를 필드 유형 다음에 포함 할 수 있습니다. 예를 들어, 부호없는 short 값을 읽습니다. 각 유형 - 개수 쌍은 가상 커서를 이진 데이터로 이동하고 현재 위치에서 바이트를 읽습니다 커서는 처음에 데이터의 시작 부분에 위치 0에 있습니다. 유형은 다음 문자 중 하나 일 수 있습니다. 데이터는 길이가 count 인 바이트 문자열입니다. count가 있으면 문자열의 나머지 바이트가 모두 변수 count가 생략되면 1 바이트가 스캔됩니다. 스캔 된 모든 바이트는 u0000 - u00ff 범위의 문자로 해석되므로 문자열이 이진 문자열 또는 ISO 8859로 인코딩 된 문자열이 아닌 경우 인코딩 convertfrom 명령이 필요할 것입니다 -1 예를 들어, var1에 저장된 abcde 000에 해당하는 문자열로 1을 반환하고 var2에는 수정되지 않은 채로 남겨두고 var2에 유로화 문자를 저장합니다. 이 양식은 후행 공백 및 null을 제외하고는 동일합니다. 변수에 저장되기 전에 스캔 된 값에서 제거됩니다. 예를 들어, var1.b에 저장된 abc efghi와 함께 1을 반환합니다. 데이터는 순서 1로 표현 된 하위에서 상위 순서로 카운트 바이너리 숫자 문자열로 변환됩니다 및 0 문자 데이터 바이트는 처음부터 마지막 ​​순서로 스캔되어 각 바이트 내에서 비트가 낮은 순서에서 높은 순서로 취해집니다. 마지막 바이트의 추가 비트는 무시됩니다. count가 0이면 문자열의 나머지 비트는 모두 scanned count가 생략되면 1 비트가 스캔됩니다. 예를 들어, var1에 저장된 11100 및 var2.B에 저장된 1110000110100000을 반환합니다. 이 양식은 비트가 높은 순서에서 낮은 순서로 취해지는 것을 제외하고는 b와 같습니다. 각각의 바이트 예를 들어, var1에 저장된 01110 및 var2.H에 저장된 1000011100000101에 대해 2를 반환합니다. 데이터는 일련의 문자 시퀀스로 표현 된 하이 - 로우 순서의 카운트 16 진수 문자열로 바뀝니다. 0123456789abcdef 데이터 바이트가 처음부터 끝까지 스캔됩니다. 각 바이트 내에서 16 진수 숫자가 하이 - 로우 순서로 취해진 다. 마지막 바이트의 여분의 비트는 무시된다. count가 있으면 문자열의 나머지 16 진수가 모두 스캔된다. count가 생략되면 16 진수 한 자리는 예를 들어, var1에 저장된 07c 및 var2.h에 저장된 051f34에 2를 반환합니다. 이 양식은 각 바이트 내에서 역순으로 반올림되어 취해지는 것을 제외하고는 H와 같습니다. 예를 들어 2를 반환합니다. 706은 var1에 저장되고 502143은 var2.Note에 저장됩니다. 여러 바이트의 16 진수를 순서대로 구문 분석하고자하는 대부분의 코드는 H format. c를 사용해야합니다. 데이터는 8 비트 부호있는 정수로 변환되어 해당 변수에 저장됩니다 목록으로 count가 있으면 문자열의 나머지 바이트를 모두 검사합니다 count가 생략되면 하나의 8 비트 정수가 검색됩니다 예를 들어 var1에 저장된 7-122와 var2에 저장된 5가있는 2를 반환합니다. 참고 반환 된 정수는 서명되어 있지만 u로 변환 될 수 있습니다. 같은 식을 사용하여 nsigned 8 비트 수량 s 데이터는 카운트로 해석됩니다. 리틀 엔디안 바이트 순서로 표현 된 16 비트 부호있는 정수 정수는 해당 변수에 목록으로 저장됩니다. count가 나머지 바이트의 경우 문자열이 스캔됩니다 count가 생략되면 하나의 16 비트 정수가 검색됩니다 예를 들어, var1에 저장된 5 7과 var2에 저장된 -16을 반환합니다. 반환되는 정수는 부호가 있지만 참고로 변환 할 수 있습니다. unsigned 16 비트 수량을 같은 식을 사용하여 반환합니다. 이 형식은 데이터가 빅 엔디안 바이트 순서로 표현 된 카운트 16 비트 부호있는 정수로 해석된다는 점을 제외하면 s와 같습니다. 예를 들어, var1에 저장된 5 7을 반환합니다. -16은 var2.t에 저장됩니다. 데이터는 카운트로 해석됩니다. Tcl 스크립트를 실행하는 시스템의 기본 바이트 순서로 표현 된 16 비트 부호있는 정수 그렇지 않으면 s 및 S와 동일합니다. 시스템의 기본 바이트 순서 바이트 오더를 참조하십시오. tclplatform 배열의 요소 i 데이터는 카운트로 해석됩니다 리틀 엔디안 바이트 순서로 표현 된 32 비트 부호있는 정수 정수는 해당 변수에 목록으로 저장됩니다 count가 있으면 문자열의 나머지 바이트가 모두 스캔됩니다 If count가 생략되면 하나의 32 비트 정수가 검색됩니다. 예를 들어, var1에 저장된 7과 var2에 저장된 -16을 반환합니다. 반환되는 정수는 부호가 있지만 부호없는 32 비트 수량으로 변환 될 수 있습니다. I 같은 식을 사용합니다. 이 형식은 데이터가 카운트로 해석된다는 것을 제외하고는 동일합니다. 빅 엔디안 바이트 순서로 표현 된 32 비트 부호있는 정수 예를 들어, var1에 저장된 5 7과 2에 저장된 -16을 반환합니다. var2.n 데이터는 카운트로 해석됩니다. Tcl 스크립트를 실행하는 시스템의 기본 바이트 순서로 표현 된 32 비트 부호있는 정수 그렇지 않으면 i 및 I와 동일합니다. 시스템의 기본 바이트 순서를 결정하려면 다음을 참조하십시오. tc의 byteOrder 요소 lplatform 배열 w 데이터는 카운트로 해석됩니다 리틀 엔디안 바이트 순서로 표현 된 64 비트 부호있는 정수 정수는 해당 변수에 목록으로 저장됩니다 count가 있으면 문자열의 나머지 바이트를 모두 스캔합니다 count가 생략되면 , 하나의 64 비트 정수가 스캔 될 것입니다. 예를 들어, var64에 저장된 var1과 -16에 저장된 30064771077과 함께 2를 반환합니다. 반환되는 정수는 부호이고 Tcl은 부호없는 값으로 나타낼 수 없습니다. 이 양식은 동일합니다 데이터가 카운트로 해석되는 것을 제외하고는 빅 엔디 언 바이트 순서로 표현 된 64 비트 부호있는 정수 예를 들어, var1에 저장된 21474836487 및 var2.m에 저장된 -16을 반환합니다. 데이터는 카운트 64 비트로 해석됩니다 Tcl 스크립트를 실행하는 컴퓨터의 네이티브 바이트 순서로 표시된 부호있는 정수 그렇지 않으면 w 및 W와 동일합니다. 컴퓨터의 기본 바이트 순서를 확인하려면 tclplatform 배열의 byteOrder 요소를 참조하십시오. f 데이터가 i입니다. 기계에서 단 정밀도 부동 소수점 수를 계산합니다. n 네이티브 표현 부동 소수점은 해당 변수에 목록으로 저장됩니다. count가 있으면 문자열의 나머지 바이트가 모두 스캔됩니다. count가 생략되면 하나의 단일 - precision 부동 소수점 수를 스캔합니다. 부동 소수점 수의 크기는 아키텍처에 따라 다를 수 있으므로 스캔되는 바이트 수가 다를 수 있습니다. 데이터가 유효한 부동 소수점 수를 나타내지 않으면 결과 값이 정의되지 않고 컴파일러에 종속됩니다 예를 들어, Intel Pentium 프로세서에서 실행되는 Windows 시스템에서는 var1r에 1 6000000238418579가 저장된 1을 반환합니다. 이 형식은 데이터가 리틀 엔디안에서 단 정밀도 부동 소수점 수로 해석된다는 점을 제외하면 f와 같습니다 order이 변환은 IEEE 부동 소수점 표현을 사용하지 않는 소수의 시스템에 이식 할 수 없습니다. R이 형식은 데이터가 c로 해석된다는 점을 제외하고는 f와 같습니다 빅 엔디안 순서로 단 정밀도 부동 소수점 숫자를 ount 변환합니다. 이 변환은 IEEE 부동 소수점 표현을 사용하지 않는 소수의 시스템에 이식 할 수 없습니다. d이 형식은 데이터가 count 배정 밀도 부동 소수점 수로 해석된다는 점을 제외하면 f와 같습니다 시스템의 기본 표현 예를 들어, Intel Pentium 프로세서에서 실행되는 Windows 시스템에서 1을 반환하고 1은 60000100000000001을 var1.q로 반환합니다. 이 형식은 데이터가 카운트 배정 밀도 플로팅 리틀 엔디 언 순서로 소수점 숫자 변환이 변환은 IEEE 부동 소수점 표현을 사용하지 않는 소수의 시스템에서는 이식 가능하지 않습니다. Q이 형식은 데이터가 빅 엔디안 순서로 카운트 배정 밀도 부동 소수점 수로 해석된다는 점을 제외하면 d와 같습니다 이 변환은 IEEE 부동 소수점 표현을 사용하지 않는 소수의 시스템에서 이식 할 수 없습니다. x 커서를 앞으로 이동합니다. string에서 count 바이트를 찾습니다. count가 크거나 클 경우 han 현재의 커서 위치 이후의 바이트 수를 지정하면 string의 마지막 바이트 다음에 커서가 위치합니다. count가 생략되면 커서는 1 바이트 앞으로 이동합니다. 이 유형은 인수를 사용하지 않습니다. 예를 들어, 1을 반환합니다. 0304가 var1.X에 저장 됨 커서를 뒤로 이동합니다. count가 문자열에있는 경우 count가 현재 커서 위치보다 크거나 같으면 커서가 위치 0에 배치되어 다음에 스캔 된 바이트가 문자열의 첫 번째 바이트가됩니다. count 이 생략되면 커서가 1 바이트 뒤로 이동합니다. 이 유형은 인수를 소비하지 않습니다. 예를 들어 var1에 저장된 1 2와 var2에 저장된 020304를 반환합니다. count로 지정된 데이터 문자열의 절대 위치로 커서를 이동합니다. 위치 0은 string의 첫 번째 바이트를 참조합니다. count가 문자열의 끝을 초과하는 위치를 참조하면 커서는 마지막 바이트 다음에 위치합니다. count가 생략되면, 예를 들어 오류가 발생합니다. var1에 저장된 1 2와 var2에 저장된 020304를 반환합니다. r R q 및 Q 변환은 모두 IEEE 부동 소수점 표현을 사용하는 컴퓨터간에 데이터를 전송하는 경우에만 안정적으로 작동합니다. 매우 보편적이지는 않지만 보편적이지 않음. 모든 아키텍처간에 부동 소수점을 이식 가능하게 전송하려면 형식으로 생성 된 텍스트 표현을 사용하십시오. 이진 인코딩 채널에 UTF-8 데이터 앞에 Tcl 문자열을 쓰는 절차입니다. 이 프로시 저는 이전에 제공된 writeString 프로 시저에 의해 작성된 채널에서 문자열을 읽습니다. 이것은 filename 파일에있는 파일의 내용을 base64로 변환하고 print Numeric Base Converter. 하나의베이스에서 다른베이스로의 변환 번호. 이베이스 컨버터는 2에서 36 사이의 변환을 지원합니다. 10보다 큰베이스에 대해서는 A 10, B 11, C 12 등이 있습니다. 잘못된 입력입니다. 그 이후의 부분은 완전히 무시됩니다. 정수 부분에 유효하지 않은 입력이 있으면 숫자로 잘못된 입력 전에 아무 것도 사용합니다. 나이는 기본으로 6입니다. 몇 살입니까? base 10. 안녕하세요, 저는 바이너리입니다. 바이너리 힌트 바이너리 2. Nick Exner 저의 독자적인 자바 애플릿 1 15 2001. Grant Young의 JavaScript HTML5 Rewrite 5 29 2014. 시리얼 링크를 통한 이진 데이터를 3 진으로 인코딩하는 방법 코드 이진 데이터는 수신되어 이진 코드로 매핑된다. 이진 코드는 삼원 코드로 변환되고, 삼항 코드는 직렬 링크를 통해 전송된다. 삼원 코드는 소정의 프로토콜에 따라 선택적으로 반전되어 직렬 링크가 시간 - 평균 제로 DC b 알란스. 직렬 링크를 통해 3 진 데이터로서 전송할 2 진 데이터를 인코딩하는 방법으로서, 2 진 데이터를 수신하는 단계와, 상기 2 진 데이터를 2 진 코드로 맵핑하는 단계와, 상기 3 진 코드가 상기 상태 레지스터가 제 1 상태에있을 때 상기 직렬 링크가 양의 DC 밸런스를 나타내는 것을 나타내는 상태 레지스터를 검사함으로써 상기 직렬 링크가 양의 직류 DC 밸런스를 갖는지 여부를 결정하는 단계와, 상기 직렬 링크가 양의 DC 평형을 갖고 상기 삼원 코드가 양의 밸런스 인 경우 상기 이진 코드를 양의 밸런스로 반전시키고 상기 이진 코드를 상기 삼진 코드로 변환하는 단계를 포함하는 방법. 제 1 항에있어서, 상기 이진 데이터의 값을 검사하는 단계를 포함하고, 상기 이진 데이터의 값이 미리 결정된 값보다 작은 경우, 상기 이진 데이터에 대한 이진 코드는 양의 평형을 이룬다 제 2 항에있어서, 상기 미리 결정된 값은 245이고 상기 소정의 상태는 논리 하이 인 것을 특징으로하는 방법. 제 1 항에있어서, 상기 제 1 상태는 논리 하이 제 1 항에있어서, 상기 3 진 코드를 반전하는 단계는 상기 2 진 코드가 3 진 코드로 변환되기 전에 상기 2 진 코드를 반전하는 단계를 포함하는 방법. 제 1 항에있어서, 상기 2 진 데이터는 8 비트를 포함하는 방법. 제 7 항에있어서, 상기 이진 코드는 12 비트를 포함하는 것을 특징으로하는 방법. 제 7 항에있어서, 상기 삼원 코드는 6 개의 3 진 심볼을 포함하는 것을 특징으로하는 방법. 제 8 항에있어서, 상기 이진 코드를 3 진 코드로 변환하는 단계는 직렬 링크를 통해 3 진 데이터로서 전송하기 위해 2 진 데이터를 인코딩하는 방법으로서, 2 진 데이터를 수신하는 단계; 2 진 데이터를 수신하는 단계; 2 진 데이터를 수신하는 단계; 2 진 데이터를 수신하는 단계; 상기 직렬 링크가 네가티브 밸런스인지 여부를 결정하는 단계와, 상기 직렬 링크가 음의 DC DC 밸런스를 갖는지 여부를 결정하는 단계와, 직렬 레지스터가 음의 DC 밸런스를 갖고 삼원 코드가 음의 밸런스 인 경우 이진 코드를 반전시키고 이진 코드를 삼항 코드로 변환하는 단계를 포함한다. 방법 제 10 항에있어서, 상기 제 1 상태는 논리 하이이다. 직렬 링크로부터 수신 된 3 진 코드를 2 진 데이터로 디코딩하는 방법으로서, 상기 3 진 코드를 수신하는 단계와, 상기 3 진 코드를 2 진 코드로 변환하는 단계를 포함하는 방법. 상기 삼원 코드가 제로인지 여부를 결정하는 단계; 상기 삼원 코드가 0 인 경우 상기 이진 코드를 이진 데이터로 매핑하는 단계; 상기 삼원 코드가 양수인지 여부를 결정하는 단계; 직렬 링크는 제로 코드가 양의 밸런스 인 경우 상태 레지스터를 검사하여 상태 DC 레지스터를 검사하여 상태 레지스터의 첫 번째 상태가 직렬 링크의 제로 DC 균형을 나타냄으로써 제로 DC 균형을 갖습니다. 삼원 코드 는 양의 밸런스이고 직렬 링크는 제로 DC 밸런스를 갖는다. 삼원 코드가 음의 밸런스인지 여부를 결정한다. 직렬 링크에 양의 DC 밸런스가 있는지 여부를 결정한다. 직렬 링크에 음의 밸런스가있는 경우 바이너리 코드를 반전시킨다. 상기 직렬 링크가 양의 DC 밸런스를 갖고 상기 삼원 코드가 음의 밸런스 인 경우 상기 이진 코드를 반전시킨 후 상기 이진 코드를 이진 데이터로 맵핑하는 단계를 더 포함하는 방법. 제 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