/*- * Copyright (c) 2007 Wojciech A. Koszek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * [id for your version control system, if any] */ #include #include #include #include /* * Zwraca binarną reprezentację liczny typu int. */ static char * pb(int x) { char s[64]; int i; int j; memset(s, '0', sizeof(s)); j = 31; i = 1; s[j + 1] = '\0'; while (j >= 0) { if (x & i) s[j] = '1'; i *= 2; j--; } return (strdup(s)); } /* * każda bramka tutaj to XOR. * * IN4 -------+-------------------- out4 * +===__ * | \ * | ,'------------- out3 * IN3 -------+==+-+ * | * +===__ * | \ * | ,'------------- out2 * IN2 -------+==+-+ * | * +===__ * | \ * | ,'------------- out1 * IN1 -------+==+-+ * | * +===__ * | \ * | ,'------------- out0 * IN0 -------+==+-+ * */ /* * A bit of bitwise magic. */ static int wk_gray(int n) { int r; int idx; int k; int i1, i2; idx = sizeof(n) * 8; idx -= 1; /* should be 31 */ assert(idx == 31); r = (n >> idx); r <<= idx; while (idx >= 1) { i1 = (n >> idx); idx -= 1; i2 = (n >> idx); k = i1 ^ i2; r |= k << idx; } return (r); } int main(int argc __unused, char **argv __unused) { int i; int gc; char *s; #define N 64 printf("i\tgc\tdesc\n"); for (i = 0; i < N; i++) { gc = wk_gray(i); s = pb(gc); assert(s != NULL && "niemozliwe"); printf("%d[%x]\t%d[%x]\t%s\n", i, i, gc, gc, s); free(s); } exit(EXIT_SUCCESS); }