C, How to save String into binary file? - mysql

I want to save String array to binary file.
I searched and tried, didn't come up with normal binary file contents.
(not like 00 0A 10) came up with (8죅? <죅? A죅? E죅?) - written in korean.
the writing part of the code was
FILE *fp_course = fopen("KJH_course.dat", "wb");
while ((row = mysql_fetch_row(res)) != NULL) { //JUST FOR FETCHING DATA FROM MYSQL, WORKED WELL
printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);
fwrite(row, sizeof(row), 1, fp_course);
};
the data in row is {'32141183', 'JHK', '2'}
(the last row[3] was used for larger array later)
did i wrote something wrong?

The MySQL documentation has an example:
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s] ", (int) lengths[i],
row[i] ? row[i] : "NULL");
}
printf("\n");
}
Note that MYSQL_ROW returned does not necessarily have nul terminated strings (as per a comment, quoted below), so you can't safely call strlen() on the columns - instead you have to call mysql_fetch_lengths().
MYSQL_ROW is an array of null-terminated strings. (However, you cannot treat these as null-terminated strings if field values may contain binary data, because such values may contain null bytes internally.)

The sizeof operator does not return the length of a string, I suppose that row is a pointer, sizeof it is simply the size of a pointer, you can't do what you want the way you tried.
You need the length of each item, so
for (int i = 0; i < 4 ; ++i) {
fwrite(row[i], 1, strlen(row[i]), fp_course);
}
VERY IMPORTANT NOTE
The contents written to the file this way, are useless, because you don't know the length of each string so there is no way to read them back.
So perhaps you are required to do something like
for (int i = 0; i < 4 ; ++i) {
char *string;
int length;
string = row[i];
length = strlen(string);
fwrite(&length, sizeof(length), 1, fp_course);
fwrite(string, 1, length, fp_course);
}
this way you can read the data back.

Related

Autokey Encryption

I am working on a project to write to and read from a TP Link / Kaza power strip or smart plug.
The data that is sent is encrypted json that has been "autokey encrypted".
So far I have been able to convert a typescript encrypt function and it works well. I get the expected result. However, I need to add a "header" to my encrypted data. That data is 3 null bytes followed by a byte that is a measure of the length of the encrypted bytes.
The typescript example has this bit of code to "encrypt with headers", however, I've hit a bit of a wall trying to convert it to something usable. Can someone nudge me along the path ?
First are the two typescript functions: (borrowed from https://github.com/plasticrake/tplink-smarthome-crypto/blob/master/src/index.ts)
/**
* Encrypts input where each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer
*/
export function encrypt(input: Buffer | string, firstKey = 0xab): Buffer {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = buf[i];
}
return buf;
}
/**
* Encrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer with header
*/
export function encryptWithHeader(
input: Buffer | string,
firstKey = 0xab
): Buffer {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
}
Second is what I have so far.
// This part works well and produces the expected results
String encrypt(String input)
{
int16_t firstKey = 0xab;
String buf;
int key;
int i;
buf = input;
key = firstKey;
i = 0;
for (;i < buf.length();(i = i + 1))
{
buf[i] ^= key;
key = buf[i];
}
return buf;
}
// This does not function yet, as I'm pretty lost..
// This was orginally converted from typescript with https://andrei-markeev.github.io/ts2c/
// I started work on converting this, but ran into errors I don't know how to solve.
String encryptWithHeader(String input){
String msgBuf;
String outBuf;
int16_t firstKey = 0xab;
char * null = NULL;
msgBuf = encrypt(input);
outBuf = msgBuf.length() +1;
//this is where I got lost...
assert(null != NULL);
null[0] = '\0';
strncat(null, outBuf, msgBuf.length());
str_int16_t_cat(null, 4);
outBuf = msgBuf + 4
return outBuf;
}
Finally, the data:
//this is the unencrypted json
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
//current encrypt function produces:
d0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
//the working "withheaders" should produce:
00002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
Admittedly my C/C++ ability is very limited and I can spell typescript, that's about all. I have a very extensive history with PHP. As useful as that is. So, I understand the basics of data structures and whatnot, but I'm venturing off into areas I've never been in. Any help would be greatly appreciated.
It looks like the encryption is fairly simple: write the current character XORed with the key to the buffer and make that newly written character the new key. It also looks like the "withHeaders" version adds the length of the encrypted string as a 4 byte integer to the start of the buffer. I think it might be easier to allocate a character array and pass that array to a function that writes the result to that buffer. For example:
void encryptWithHeader(byte buffer[], int bufferLength, byte key, String message) {
int i;
uint32_t messageLength = message.length();
Serial.println(message);
Serial.println(message.length());
// check that we won't overrun the buffer
if ( messageLength + 5 < bufferLength) {
buffer[0] = messageLength >> 24 & 0xFF;
buffer[1] = messageLength >> 16 & 0xFF;
buffer[2] = messageLength >> 8 & 0xFF;
buffer[3] = messageLength & 0xFF;
for (i = 0; i < messageLength; i++) {
buffer[i + 4] = message[i] ^ key;
key = buffer[i + 4];
}
}
else { // we would have overrun the buffer
Serial.println("not enough room in buffer for message");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
byte theBuffer[64];
int i;
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
encryptWithHeader(theBuffer, 64, 0xab, offMsg);
// now print it out to check
for (i = 0; i < offMsg.length() + 4; i++) {
if (theBuffer[i] < 0x10) // adds an extra zero if a byte prints as on1y 1 char
Serial.print("0");
Serial.print(theBuffer[i], HEX);
}
while (true)
;
}
If you want to send the character buffer to a remote device you can send it out one byte at a time:
for (i = 0; i < offMsg.length() + 4; i++)
Serial.write(theBuffer[i]);

Buffering output in C without using FILE

I'm trying to create a full HTML result with HTTP headers with the correct size for content-length as simple as possible.
I looked at setbuf() function but it only works with streams, but I want to directly buffer the output to memory without having a disk involved. Is there a simpler function that does what I'm trying to achieve?
I know in php, one can use ob_start() to start buffering data and ob_get_contents() to load the data in memory and determine the size so is there anything like this in C that I can use?
int main(){
char *mybuf=malloc(1048576); //Allocate 1MB memory for buffer
char *mytitle="Webpage title";
char *mydesc="This is a page version";
int myver=2;
//print HTTP header of known data
printf("HTTP/1.1 200 OK\r\n");
printf("Server: Something\r\n");
printf("Content-type: text/html; charset=UTF-8\r\n");
printf("Cache-control: no-cache\r\n");
//Buffer HTML output to get size (we don't print these 4 lines yet)
sprintf(mybuf,"<html><head><title>%s</title></head><body>\r\n",mytitle);
sprintf(mybuf+strlen(mybuf),"<h1>%s</h1>\r\n",mytitle);
sprintf(mybuf+strlen(mybuf),"<p>%s %d</p>\r\n",mydesc,myver);
sprintf(mybuf+strlen(mybuf),"</body></html>\r\n");
//Print content length header with size of buffered data
printf("Content-length: %d\r\n",strlen(mybuf));
//then print the rest of the data
printf("%s",mybuf);
free(mybuf);
return 0;
}
The C language specification does not define any facility for streams backed only by memory, without any underlying file. Your sprintf() based approach is not bad, but it could be improved by capturing and using the return value, which tells you how many characters were printed. You could use this to avoid all the strlen() calls, which could be a considerable savings if the content is large, especially if it is printed in many small pieces:
size_t total_bytes_written = 0;
long rval;
rval = sprintf(mybuf, "<html><head><title>%s</title></head><body>\r\n", mytitle);
if (rval < 0) {
// handle error ...
}
total_bytes_written += rval;
rval = sprintf(mybuf + total_bytes_written, "<h1>%s</h1>\r\n", mytitle);
// ...
Alternatively, if you are on a system that conforms to POSIX.1-2008 or later, and you are willing to limit your program to such systems, then you might find open_memstream() of interest. This gives you a stream backed by a dynamically managed block of memory. You would write to it with fprintf() or other stream IO functions, and when done, read back a pointer to the data and the total size. Something like this:
char *buf_ptr = NULL;
size_t buf_size = 0;
FILE *mem = open_memstream(&buf_ptr, &buf_size);
fprintf(mem, "<html><head><title>%s</title></head><body>\r\n", mytitle);
fprintf(mem, "<h1>%s</h1>\r\n", mytitle);
// ...
fclose(mem); // mandatory
printf("Content-length: %d\r\n", buf_size);
printf("%s", buf_ptr); // the data are guaranteed null-terminated
free(buf); // you are responsible for this
(All error checks omitted for brevity.)
This relieves you of the manual size tracking, and it gains you a dynamically-growing backing buffer so that you can handle both large and small outputs with reasonable memory efficiency.
There are multiple solutions to this problem:
your approach is OK, but you should use snprintf() to avoid potential buffer overflows:
int main() {
char *mybuf = malloc(1048576); //Allocate 1MB memory for buffer
const char *mytitle = "Webpage title";
const char *mydesc = "This is a page version";
int myver = 2;
size_t pos = 0;
//print HTTP header of known data
printf("HTTP/1.1 200 OK\r\n");
printf("Server: Something\r\n");
printf("Content-type: text/html; charset=UTF-8\r\n");
printf("Cache-control: no-cache\r\n");
//Buffer HTML output to get size (we don't print these 4 lines yet)
pos += snprintf(mybuf + pos, pos < sizeof mybuf ? sizeof mybuf - pos : 0,
"<html><head><title>%s</title></head><body>\r\n", mytitle);
pos += snprintf(mybuf + pos, pos < sizeof mybuf ? sizeof mybuf - pos : 0,
"<h1>%s</h1>\r\n", mytitle);
pos += snprintf(mybuf + pos, pos < sizeof mybuf ? sizeof mybuf - pos : 0,
"<p>%s %d</p>\r\n", mydesc, myver);
pos += snprintf(mybuf + pos, pos < sizeof mybuf ? sizeof mybuf - pos : 0,
"</body></html>\r\n");
//Print content length header with size of buffered data
printf("Content-length: %zu\r\n", pos);
printf("\r\n");
//then print the rest of the data
printf("%s", mybuf);
free(mybuf);
return 0;
}
Here is a simpler one, combining the calls and using snprintf to compute the length:
int main() {
const char *mytitle = "Webpage title";
const char *mydesc = "This is a page version";
int myver = 2;
size_t length = 0;
//print HTTP header of known data
printf("HTTP/1.1 200 OK\r\n");
printf("Server: Something\r\n");
printf("Content-type: text/html; charset=UTF-8\r\n");
printf("Cache-control: no-cache\r\n");
//Buffer HTML output to get size (we don't print these 4 lines yet)
length = snprintf(NULL, 0,
"<html><head><title>%s</title></head><body>\r\n"
"<h1>%s</h1>\r\n"
"<p>%s %d</p>\r\n"
"</body></html>\r\n",
mytitle, mytitle, mydesc, myver);
//Print content length header with size of buffered data
printf("Content-length: %zu\r\n", length);
printf("\r\n");
//then print the rest of the data
printf("<html><head><title>%s</title></head><body>\r\n"
"<h1>%s</h1>\r\n"
"<p>%s %d</p>\r\n"
"</body></html>\r\n",
mytitle, mytitle, mydesc, myver);
return 0;
}
you could use open_memstream() as explained by John Bollinger:
int main() {
const char *mytitle = "Webpage title";
const char *mydesc = "This is a page version";
int myver = 2;
size_t length = 0;
char *buf_ptr = NULL;
size_t buf_size = 0; // the buffer size
int length = 0; // the length of the output
FILE *mem = open_memstream(&buf_ptr, &buf_size);
//print HTTP header of known data
printf("HTTP/1.1 200 OK\r\n");
printf("Server: Something\r\n");
printf("Content-type: text/html; charset=UTF-8\r\n");
printf("Cache-control: no-cache\r\n");
//Buffer HTML output to get size (we don't print these 4 lines yet)
if (mem == NULL) {
// Deal with the error
printf("Internal error\r\n");
return 1;
}
length = fprintf(mem,
"<html><head><title>%s</title></head><body>\r\n"
"<h1>%s</h1>\r\n"
"<p>%s %d</p>\r\n"
"</body></html>\r\n",
mytitle, mytitle, mydesc, myver);
//Print content length header with size of buffered data
printf("Content-length: %zu\r\n", length);
printf("\r\n");
//then print the rest of the data
//beware that buf_ptr is not necessarily null terminated
printf("%.*s", length, buf_ptr);
//could also use fwrite(f, buf_ptr, 1, length, stdout);
free(buf_ptr);
return 0;
}
you can implement your own mem_printf() that allocates or reallocates a memory buffer:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int mem_printf(char **bufp, size_t *lenp, const char *fmt, ...) {
char buf[1024];
va_list ap;
char *newbuf;
int len;
va_start(ap, fmt);
len = vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
if (len < 0)
return -1;
newbuf = realloc(*bufp, *lenp + len + 1);
if (newbuf == NULL)
return -1;
*bufp = newbuf;
if ((size_t)len < sizeof buf) {
memcpy(newbuf + *lenp, buf, len + 1);
} else {
va_start(ap, fmt);
vsnprintf(newbuf + *lenp, len + 1, fmt, ap);
va_end(ap);
}
*lenp += len;
return len;
}
int main() {
const char *mytitle = "Webpage title";
const char *mydesc = "This is a page version";
int myver = 2;
char *buf_ptr = NULL;
size_t buf_len = 0;
//print HTTP header of known data
printf("HTTP/1.1 200 OK\r\n");
printf("Server: Something\r\n");
printf("Content-type: text/html; charset=UTF-8\r\n");
printf("Cache-control: no-cache\r\n");
//Buffer HTML output to get size (we don't print these 4 lines yet)
mem_printf(&buf_ptr, &buf_len,
"<html><head><title>%s</title></head><body>\r\n"
"<h1>%s</h1>\r\n"
"<p>%s %d</p>\r\n"
"</body></html>\r\n",
mytitle, mytitle, mydesc, myver);
//Print content length header with size of buffered data
printf("Content-length: %zu\r\n", buf_len);
printf("\r\n");
//then print the rest of the data
fputs(buf_ptr, stdout);
free(buf_ptr);
return 0;
}
Content-Length, as you probably know, is the size of your body. This means you have to know at least the length of the body before you can generate the header (or use chunked transfer). sprintf returns the number of bytes written, either accumulate those, or squash it into a single call:
int n = snprintf(mybuf,
mybuf_len,
"<html><head><title>%s</title></head><body>\r\n"
...
"</body></html>\r\n",
mytitle, ..., myver
);
Then generate the header(n) with the n you figured out. If you pass in NULL for instead of mybuf, you get a size without writing anything, then you could do another write a pass in header with the count you got from the first call. If you want, wrap this in a function or two:
int response(const char *header, int body_len, const char body[body_len]) {
...
}
Consider picking a template library (I like the mustache format). It's kinda messy and error prune doing this by hand with raw strings. You have a 1 MB buffer allocated there but use like a .5k, and you will shoot yourself in the foot one day anyhow.

My value in my variable disapears (does not print) if i add or subtract a value

I am making a project for school and i need to make a system that keeps the temperature around a set temperature (this is done by a phidget sensor and turning a heating and cooling
element on and off.) the sensors values can be converted to degrees celcius with the formula ((Current Temperature + 50)*4) and i got it working for a stactic 20 degrees celcius, but now i am trying to get a temprature from a database and keep it around that temprature instead(so the temprature can be changed inside the room where the heating and cooling elements are). but when i try to convert the temperature that i got from the database to the sensor value with the formula the temp variable starts giving random numbers and i dont know why. Can someone explain or help?
(See comment toward bottom of code example for problem location)
//my code is a code written for controlling the temprature in a room
//this is done by a phidget sensor and turning a heating and cooling
//element on and of.
#include <phidget21.h> // voor phidgetfucties
#include <stdio.h> // voor printf()
#include <mysql/mysql.h> // voor mysql querys
#include <my_global.h>
int main (int argc, char* argv[])
{ //variables
int val;
int gewensteTempratuur = 280;
int gewensteGradenCelcius = 0;
int i = 0;
int temp = 0;
CPhidgetInterfaceKitHandle ifKit = 0;
CPhidgetInterfaceKit_create(&ifKit);
CPhidget_open((CPhidgetHandle)ifKit,-1);
for(;;)
{
CPhidgetInterfaceKit_getSensorValue(ifKit,0,&val);
printf("Value %d \n", val);
if(val < (gewensteTempratuur - 4)){
//verwarming
CPhidgetInterfaceKit_setOutputState(ifKit,0,1);
//airco
CPhidgetInterfaceKit_setOutputState(ifKit,1,0);
}
if(val > (gewensteTempratuur + 4)){
//verwarming
CPhidgetInterfaceKit_setOutputState(ifKit,0,0);
//airco
CPhidgetInterfaceKit_setOutputState(ifKit,1,1);
}
if((val < (gewensteTempratuur + 4)) && (val > (gewensteTempratuur - 4))) {
//verwarming
CPhidgetInterfaceKit_setOutputState(ifKit,0,0);
//airco
CPhidgetInterfaceKit_setOutputState(ifKit,1,0);
}
//Database Connection
MYSQL *conn;
//Verbings gegevens
char *server = "server";
char *user = "user";
char *password = "pass";
char *database = "database";
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
}
//getting information from the database
if (mysql_query(conn, "SELECT Gewenstetemperatuur FROM SensorValue")){
mysql_error(conn);
}
MYSQL_RES *result = mysql_store_result(conn);
if (result == NULL){
mysql_error(conn);
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result))){
for (i = 0; i < num_fields; i++){
printf("%s ", row[i] ? row[i] : "NULL");
gewensteGradenCelcius = (int)row[i];
temp = gewensteGradenCelcius;
printf("\n %s \n", gewensteGradenCelcius);
printf("%d \n",temp )
//Here is were is get stuck if i try to take the value and run it trough a
//formula like (gewensteGradenCelcius + 50) * 4 and the try to print the
//gewensteGradenCelcius just puts out nothing
}
printf("\n");
}
mysql_free_result(result);
usleep(1500000);
}
}
The conversion in your code of a number contained in string format ( row[i] ) is done incorrectly....
A C string cannot be copied into an int as you have attempted. C does provide several ways to do this, including the following... Change:
gewensteGradenCelcius = (int)row[i];//incorrect
To:
//EITHER
gewensteGradenCelcius = atoi(row[i]);//simple and legal C99, but not recommended
//OR
char *endptr;
gewensteGradenCelcius = (int)strtol(row[i], &endptr, 10);//recommended method
//OR
sscanf(row[i], "%d",&gewensteGradenCelcius);//recommended method
( why atoi() is not recommended )
Then, because gewensteGradenCelcius is an int your printf statement, use an int format specifier. Change:
printf("\n %s \n", gewensteGradenCelcius);//wrong format specifier for int
To:
printf("\n %d \n", gewensteGradenCelcius);//correct format specifier
^^
row[i] is a text (line "20" or "18"), so this line is wrong:
gewensteGradenCelcius = (int)row[i];
and you shoud rather write
gewensteGradenCelcius = atoi(row[i]);

Fetch MySQL row result to dynamic array

When a retrieve info from my db fetch_row(result)
I want to select from these results and store them in a dynamic array
row[i] will be the info a need
I'll need to store it to tagid[trigger]
but char* can be stored to char
so what i now is tagid[trigger] = *row[i];
but when i check the results... it aint what i want
the number 358713020035990 needs to be in tagid...
row[i] 0x05df2090 "358713020035990" char *
tagid[i] -112 '' char
how do i get this right?
char *tagid;int trigger;
tagid = (char *) malloc(sizeof(char));
result = mysql_store_result(conn); // only one column of integers
num_rows = mysql_num_rows(result);
while (row = mysql_fetch_row(result))
{tagid[trigger] = *row[i];}
If you are trying to copy a string data buffer, and not just the pointer to that buffer, then you are going to have to use a memory copy operation or preferably a standard library function made for such purposes like strcpy, or strncpy. So assuming that tagid[trigger] is referring to a block of memory that is an array of type char, you could do the following:
#include <string.h>
//tagid is a two-dimensional array of chars of ROWSIZE x COLUMNSIZE
char** tagid;
tagid = malloc(sizeof(char*) * COLUMNSIZE);
for (int i=0; i < COLUMNSIZE; i++)
{
tagid[i] = malloc(sizeof(char) * ROWSIZE);
}
//copy some data into your array at row index "trigger"
int trigger = SOMEVALUE;
strncpy(tagid[trigger], row[i], ROWSIZE);
//free the memory you've allocated for your two dimensional array
for (int i=0; i < COLUMNSIZE; i++)
{
free(tagid[i]);
}
free(tagid);
The value of ROWSIZE will have to be big enough to hold your largest string plus a terminating NULL otherwise the copy will be truncated using strncpy, or the data will overflow the array bounds and will write-over something else you don't want it to if you use strcpy.

Best algorithm to find all possible permutation of given binary bits

I am looking for an optimal algorithm to find out remaining all possible permutation
of a give binary number.
For ex:
Binary number is : ........1. algorithm should return the remaining 2^7 remaining binary numbers, like 00000001,00000011, etc.
Thanks,
sathish
The example given is not a permutation!
A permutation is a reordering of the input.
So if the input is 00000001, 00100000 and 00000010 are permutations, but 00000011 is not.
If this is only for small numbers (probably up to 16 bits), then just iterate over all of them and ignore the mismatches:
int fixed = 0x01; // this is the fixed part
int mask = 0x01; // these are the bits of the fixed part which matter
for (int i=0; i<256; i++) {
if (i & mask == fixed) {
print i;
}
}
to find all you aren't going to do better than looping over all numbers e.g. if you want to loop over all 8 bit numbers
for (int i =0; i < (1<<8) ; ++i)
{
//do stuff with i
}
if you need to output in binary then look at the string formatting options you have in what ever language you are using.
e.g.
printf("%b",i); //not standard in C/C++
for calculation the base should be irrelavent in most languages.
I read your question as: "given some binary number with some bits always set, create the remaining possible binary numbers".
For example, given 1xx1: you want: 1001, 1011, 1101, 1111.
An O(N) algorithm is as follows.
Suppose the bits are defined in mask m. You also have a hash h.
To generate the numbers < n-1, in pseudocode:
counter = 0
for x in 0..n-1:
x' = x | ~m
if h[x'] is not set:
h[x'] = counter
counter += 1
The idea in the code is to walk through all numbers from 0 to n-1, and set the pre-defined bits to 1. Then memoize the resulting number (iff not already memoized) by mapping the resulting number to the value of a running counter.
The keys of h will be the permutations. As a bonus the h[p] will contain a unique index number for the permutation p, although you did not need it in your original question, it can be useful.
Why are you making it complicated !
It is as simple as the following:
// permutation of i on a length K
// Example : decimal i=10 is permuted over length k= 7
// [10]0001010-> [5] 0000101-> [66] 1000010 and 33, 80, 40, 20 etc.
main(){
int i=10,j,k=7; j=i;
do printf("%d \n", i= ( (i&1)<< k + i >>1); while (i!=j);
}
There are many permutation generating algorithms you can use, such as this one:
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0) {
for (int i = 0; i < size; i++) {
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void visit(int *Value, int N, int k)
{
static level = -1;
level = level+1; Value[k] = level;
if (level == N)
print(Value, N);
else
for (int i = 0; i < N; i++)
if (Value[i] == 0)
visit(Value, N, i);
level = level-1; Value[k] = 0;
}
main()
{
const int N = 4;
int Value[N];
for (int i = 0; i < N; i++) {
Value[i] = 0;
}
visit(Value, N, 0);
}
source: http://www.bearcave.com/random_hacks/permute.html
Make sure you adapt the relevant constants to your needs (binary number, 7 bits, etc...)
If you are really looking for permutations then the following code should do.
To find all possible permutations of a given binary string(pattern) for example.
The permutations of 1000 are 1000, 0100, 0010, 0001:
void permutation(int no_ones, int no_zeroes, string accum){
if(no_ones == 0){
for(int i=0;i<no_zeroes;i++){
accum += "0";
}
cout << accum << endl;
return;
}
else if(no_zeroes == 0){
for(int j=0;j<no_ones;j++){
accum += "1";
}
cout << accum << endl;
return;
}
permutation (no_ones - 1, no_zeroes, accum + "1");
permutation (no_ones , no_zeroes - 1, accum + "0");
}
int main(){
string append = "";
//finding permutation of 11000
permutation(2, 6, append); //the permutations are
//11000
//10100
//10010
//10001
//01100
//01010
cin.get();
}
If you intend to generate all the string combinations for n bits , then the problem can be solved using backtracking.
Here you go :
//Generating all string of n bits assuming A[0..n-1] is array of size n
public class Backtracking {
int[] A;
void Binary(int n){
if(n<1){
for(int i : A)
System.out.print(i);
System.out.println();
}else{
A[n-1] = 0;
Binary(n-1);
A[n-1] = 1;
Binary(n-1);
}
}
public static void main(String[] args) {
// n is number of bits
int n = 8;
Backtracking backtracking = new Backtracking();
backtracking.A = new int[n];
backtracking.Binary(n);
}
}