Converting int array of 1's and 0's into true binary

Started by
14 comments, last by Matei 19 years, 7 months ago
#include <stdlib.h>long number = 0;int index = 0;char buffer[32];for ( index = 0; index < 32; ++index ){    if ( A[index] )        char[index] = '1';    else        char[index] = '0';}number = strtol( buffer, NULL, 2 );


edit: I asked a similar question very recently, if you store it in a character array originally with '1's and '0's then you can just call strtol();
Advertisement
Here's another flavor in the form of a function.

int arraytoint( int * A ){  int * pointer = A;  int * end = A + 31;  int returnValue = 0;  for( ; pointer <= end; ++pointer )    returnValue |= (*pointer)<<(end-pointer);  return returnValue;}


If A is a pointer to your array of ints, call:
     int x = arraytoint(A);
unsigned long array[32] = {    0,0,0,0,0,1,1,1,    0,1,1,1,1,1,0,0,    1,0,1,1,0,1,0,1,    0,0,1,1,0,0,0,1,};unsigned long bits;bits |= array[0]  << 0;bits |= array[1]  << 1;bits |= array[2]  << 2;bits |= array[3]  << 3;bits |= array[4]  << 4;bits |= array[5]  << 5;bits |= array[6]  << 6;bits |= array[7]  << 7;bits |= array[8]  << 8;bits |= array[9]  << 9;bits |= array[10] << 10;bits |= array[11] << 11;bits |= array[12] << 12;bits |= array[13] << 13;bits |= array[14] << 14;bits |= array[15] << 15;bits |= array[16] << 16;bits |= array[17] << 17;bits |= array[18] << 18;bits |= array[19] << 19;bits |= array[20] << 20;bits |= array[21] << 21;bits |= array[22] << 22;bits |= array[23] << 23;bits |= array[24] << 24;bits |= array[25] << 25;bits |= array[26] << 26;bits |= array[27] << 27;bits |= array[28] << 28;bits |= array[29] << 29;bits |= array[30] << 30;bits |= array[31] << 31;
For more obfuscation, template meta programming

template<int nbBits>
int valueOf(int* A)
{
return A[0] | (valueOf<nbBits-1>(A+1) << 1);
}

template<>
int valueOf<0>(int* A) { return 0; }

Now valueOf<32>(A) would be expanded at compile time to the good expression (if I didnt do any mistake)
Silly me..

For even more obfuscation, just program it in intercal. Maybe this is an example of how not to do it? In 16-Bit that is.

DO .1 <- #1(1) DO FORGET #1DO (1020) NEXTPLEASE DO .3 <- '?.1$#33'~'#0$#65535'DO .3 <- ".3$#1"~#3DO .2 <- !2$,1SUB.1'~'#32767$#1'DO (3) NEXTPLEASE DO (1) NEXT(3)DO (2) NEXTDO READ OUT .2PLEASE GIVE UP(2) DO RESUME .3DO REMAIN CALM A HUGE ERROR HAS OCCURRED


Where the array is ,1, the counter is .1 and the output is .2, which is outputted at the end. .3 is just a temporary used for the Xor-comparison test.
Remember to compile with the /b switch set, if you want to avoid error 774..
Aww, for a moment there I thought Gamedev.net had syntax highlighting for Intercal. It looks like it's just handling it as Basic though.

This topic is closed to new replies.

Advertisement