write 1-wire rom addres to variable - c

From a bunch of 1-wire devices I want to write the devices rom addresses to an array.
I have tried many options, but obviously I don't have a clue how to do this right.
In the code below, in the device search loop I get the adress printed on the serial line as I expect it.
But the printed output of the main loop indicates that I am way of in my method to store this address in an array....
#include <OneWire.h>
// http://www.pjrc.com/teensy/td_libs_OneWire.html
OneWire ds(2);
void setup(void) {
Serial.begin(9600);
while (!Serial) {
}
}
unsigned char UIDs[12];
int indx=0;
void getDeviceAddresses(void)
{
int i=0;
byte present = 0;
byte done = 0;
byte data[12];
byte addr[8];
while ( !done )
{
if ( ds.search(addr) != 1)
{
Serial.print("No more addresses.\n");
ds.reset_search();
done = 1;
delay(1000);
indx=0;
return;
}
else
{
Serial.print("Sensors");
Serial.print(indx);
Serial.print(" address is:\t");
indx++;
//read each byte in the address array
for( i = 0; i < 8; i++) {
//Serial.print("0x");
if (addr[i] < 16) {
Serial.print('0');
}
// print each byte in the address array in hex format
UIDs[indx]=(UIDs[indx]+(addr[i], HEX)); // I guess this is not how to do it....
Serial.print(addr[i], HEX);
}
}
Serial.println();
}
}
void loop (){
getDeviceAddresses();
int i=0;
while (true) {
for ( indx = 0; indx < 13; indx++) {
Serial.println(UIDs[indx]);
}
delay(4000);
}
}
Sensors0 address is: 106C402502080064
Sensors1 address is: 101E3C25020800DE
Sensors2 address is: 10614C250208000F
Sensors3 address is: 10513325020800E0
Sensors4 address is: 10094B250208003C
Sensors5 address is: 104D342502080097
Sensors6 address is: 10FD4025020800E2
Sensors7 address is: 10534025020800AD
Sensors8 address is: 1047672502080083
No more addresses.
0
128
128
128
128
128
128
128
128
128
0
0
12

It looks like addr is an array of 8 bytes holding your address.
If you define as:
unsigned char UIDs[12][8];
Then on each pass through your function you have:
{
Serial.print("Sensors");
Serial.print(indx);
Serial.print(" address is:\t");
indx++;
//read each byte in the address array
for( i = 0; i < 8; i++) {
//Serial.print("0x");
if (addr[i] < 16) {
Serial.print('0');
}
// print each byte in the address array in hex format
UIDs[indx][i] = addr[i];
Serial.print(addr[i], HEX);
}
}
And finally in your loop to print them:
for ( indx = 0; indx < 13; indx++) {
for (int i=0; i<8; i++){
if(UIDs[indx][i] < 16){
Serial.print('0');
}
Serial.print(UIDs[indx][i], HEX);
}

#Delta_G - Thanks!
I tried the 2 dimensional array first but could not get it right.
Think I messed up the second printing routine.
For future reference in case somebody needs this to, this is a complete working test code.
unsigned char UIDs[12][8];
byte indx=0;
byte nr_of_devices=0;
#include <OneWire.h>
// http://www.pjrc.com/teensy/td_libs_OneWire.html
OneWire ds(2);
void setup(void) {
Serial.begin(9600);
while (!Serial) {
}
}
void getDeviceAddresses(void)
{
int i=0;
byte present = 0;
byte done = 0;
byte data[12];
byte addr[8];
while ( !done )
{
if ( ds.search(addr) != 1)
{
Serial.print("No more addresses.\n");
ds.reset_search();
done = 1;
delay(1000);
nr_of_devices=indx;
indx=0;
return;
}
else
{
Serial.print("Sensors");
Serial.print(indx);
Serial.print(" address is:\t");
indx++;
//read each byte in the address array
for( i = 0; i < 8; i++) {
//Serial.print("0x");
if (addr[i] < 16) {
Serial.print('0');
}
// print each byte in the address array in hex format
UIDs[indx][i] = addr[i];
Serial.print(addr[i], HEX);
if (!i >= 1) {
Serial.print("-");
}
}
}
Serial.println();
}
}
void loop (){
getDeviceAddresses();
int i=0;
while (true) {
Serial.println("Sensors found:");
for ( indx = 1; indx < nr_of_devices; indx++) {
Serial.print(indx);Serial.print(": ");
for (int i=0; i<8; i++){
if(UIDs[indx][i] < 16){
Serial.print('0');
}
Serial.print(UIDs[indx][i], HEX);
}
Serial.println("");
}
delay(4000);
}
}

Related

Reading values from an array

I am trying to read an RFID tag and compare the RFID number with a array which I have already there. In my code, the comparing is not working properly. It always gives output as both 'Found' and 'Not found'. Can any one help me on this?
The two RFID numbers that I want to read are: 37376B34 and 7AA29B1A. These two are only for testing. I'm going to store about 20 RFID numbers in the array and check.
My code:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
int readsuccess;
byte readcard[4];
char str[32] = "";
String StrUID;
char* myTags[] = {"9FF4375C","37376B34","7AA29B1A","1B7D5223","9FF4375C"};
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
// --------------------------------------------------------------------
void loop() {
readsuccess = getid();
if (readsuccess) {
Serial.println(StrUID);
delay(1000);
}
for (int i = 0; i < 5; i++) {
if (StrUID == myTags[i]) {
Serial.println("Found");
return;
} else {
Serial.println("Not Found");
}
}
}
// --------------------------------------------------------------------
int getid() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return 0;
}
if (!mfrc522.PICC_ReadCardSerial()) {
return 0;
}
for (int i=0; i<4; i++) {
readcard[i] = mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard
array_to_string(readcard, 4, str);
StrUID = str;
}
mfrc522.PICC_HaltA();
return 1;
}
// --------------------------------------------------------------------
void array_to_string(byte array[], unsigned int len, char buffer[]) {
for (unsigned int i = 0; i < len; i++) {
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i * 2 + 0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i * 2 + 1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len * 2] = '\0';
}
Data type byte in Arduino is just unsigned char in c++. Since the data that you read from the reader are in bytes, so it is possible to directly compare it with myTags without the need of using String object or even the array to string conversion. You can do the comparison with C++ memcmp() function.
const char* myTags[] = {"9FF4375C","37376B34","7AA29B1A","1B7D5223","9FF4375C"};
byte myReading[4] = {0x9f,0xf4,0x37,0x5c};
for (int i = 0; i < 5; i++) {
if (memcmp(myTags[i], myReading, sizeof(myReading)) == 0) {
Serial.println("Found");
return;
} else {
Serial.println("Not Found");
}
}

pass multiple values from a function defined in one file to another file using c

I have a task get multiple values from one function defined in one.c file to other function defined in two.c file.
Please find below code snippet from both the files and kindly help to access the values from one.c file into two.c file.
file one.c:
void GetABFWversion(uint8_t* fwcommand, uint8_t* fwaction, uint16_t* fwvalue)
{
uint16_t FW_slot=SdusAutoDetectSlotForNewFirmware();
char MyCopy[10];
strcpy (MyCopy, BrakeBoardInfo.firmwareVersion);
char MyCopy1[10];
for (int k=0; k<9; k++)
{
int l=1;
MyCopy1[k] = MyCopy[k+l];
}
char FWversion_AB[10] = {0};
int z = 0;
for(int x=6;x<10;x++)
{
FWversion_AB[z] = MyCopy1[x];
z++;
}
char res=0;
uint16_t val = atoi(FWversion_AB);
//res = proto485OnlyWrite(0x09,0x02,0x00,val);
printf("\n");
printf("FW version is sent to Arduino!!! ");
RESULT = 1;
*fwcommand = 0x02;
*fwaction = 0x00;
*fwvalue = val;
}
file two.c:
int16_t driver485Read (uint8_t *buffer, const uint16_t length)
{
char head[20];
const char *format="KL%02x:";
int16_t wait_loop_cnt=0;
static uint32_t totalBytes = 0;
static uint32_t respNo = 0;
GPIO_ClearValue(PMAP_GPIO_PORT_DIR_RS485, PMAP_GPIO_PIN_DIR_RS485);
UartRxFlush(UARW_UART_INDEX_RS485); /
respNo++;
int counter = 0;
do
{
OSTimeDly(2);
int8_t newBytesRcv = UartReceive(UARW_UART_INDEX_RS485,
(uint8_t*)&(buffer[counter]), length-counter);
totalBytes += newBytesRcv;
counter = totalBytes;
}
while (/*wait_loop_cnt++<= MAX_WAIT_LOOP &&*/ counter < length);
totalBytes = 0;
uint8_t i = 0;
format="OK%02x:";
printf("Byte received........");
int FWmsg[9] = {0x09,0x30,0x30,0x32,0x32,0x31,0x31,0x31,0x31};
int arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};
for (i=0; i<9;i++)
{
printf("%d ",buffer[i]);
arduinodata[i] = buffer[i];
}
if(compareArray(FWmsg,arduinodata,7)==0)
{
printf("Arrays have same elements.\n");
printArray(FWmsg,9);
char res = 0;
uint8_t fwc, fwa;
uint16_t fwv;
GetABFWversion(&fwc, &fwa, &fwv);
res = proto485OnlyWrite(0x09,fwc,fwa,fwv);
printf("\n");
printf("FW version is sent to Arduino!!! ");
}
else
{
printf("Arrays have different elements.\n");
}
/* 1st byte is the slave address byte which value should be >= RS485_ADDRESS_SLAVE_FIRST &&
<= RS485_ADDRESS_SLAVE_LAST and is already checked in dePadLeft() */
for(int i = 1; i < length && buffer[i] >= RS485_PAYLOAD_VALID_MIN && buffer[i] <= RS485_PAYLOAD_VALID_MAX; i++);
counter = i; // to be OK, i = length = RS485_MSG_LENGTH if response (after eventual dePad..) is OK
printf("driver485Read %d\n",counter);
#ifdef RS485_DEBUG
static uint32_t i = 0;
i++;
#endif
return counter;
GPIO_SetValue(PMAP_GPIO_PORT_DIR_RS485, PMAP_GPIO_PIN_DIR_RS485);
}
file three.c:
uint8_t proto485OnlyWrite(uint8_t address, uint8_t command, uint8_t action, uint16_t value)
{
uint8_t res=ERROR_FOUND;
OSSemPend(pbSemaphore, 0, &res);
if (res == OS_ERR_NONE)
{
rs485_message_t rs485Msg;
if (command ==CMD_POWER_PUMP_PB)
{
printf("CMD_POWER_PUMP_PB");
}
proto485ComposeMsg(&rs485Msg, address, command, action, value);
res = (RS485_MSG_LENGTH == driver485Write((uint8_t *)&rs485Msg, sizeof(rs485Msg))) ?
NO_ERROR:
ERROR_FOUND;
OSSemPost(pbSemaphore);
}
return res;
}
I want to get the values of "fwcommand", "fwaction" and "fwvalue" defined in file one.c into file two.c at the place where I am passing the same to "res = proto485OnlyWrite(0x09,fwc,fwa,fwv);" in the place of "fwc", "fwa" and "fwv" respectively.
Thank you....

Continued Power Function Message

I keep getting the error message that my I have an undefined reference to the power function, but I'm not really sure where that is occurring or why my code is coming up with that error because I have used to power function before in this way. If anyone could help me figure out why it isn't working now I would really appreciate it.
#include "stdio.h"
#include "string.h" //Needed for strlen()
#include "math.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
#define NUMBER_TWO 2
#define NUMBER_ONE 1
#define TERMINATOR '\0'
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
last_index_of == i;
}
}
return last_index_of;
}
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (i < 1) {
out_str[i] = in_str[start] + in_str[end-1];
i++;
}
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH +1]; // +1 for '\0'
int number;
double exponent;
char output[MAX_BITS];
int fraction;
sub_string(input, output, 0, TERMINATOR);
//Input from the user
printf("Enter a floating point value in binary: ");
scanf("%s", input);
//Calculates the Decimal Part
for (int i = 0; i < last_index_of(input, TERMINATOR) ; i++) {
number = number + number + input[i];
}
printf("%d", number);
exponent = -1;
//Calculates the Fractional Part
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
if (j == last_index_of) {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d/n", fraction);
}
else {
fraction = NUMBER_ONE/(pow(NUMBER_TWO, exponent));
printf("%d + ", fraction);
exponent--;
}
}
return 0;
}
Some problems:
you need -lm option to linker to tell it where to find pow function
last_index_of is not correctly written, you use the function name as an internal variable, you can correct it this way:
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch) {
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if(in_str[i] == ch) {
ret = i;
}
}
return ret;
}
Note that you can replace your last_index_of() function by strlen()
as pointed in comment, sub_string() is not functionnal. A corrected version could be:
//Code to find the start of the fractional aspect
void sub_string(char in_str[], char out_str[], int start, int end){
int i = 0;
while (start != end) {
/* warning, bounds are still not tested...*/
out_str[i++] = in_str[start++];
}
out_str[i] = '\0'
}
Instead of calling last_index_of() in your exist for loop condition, you should take its value to re-use it:
for (int j = 0; j < last_index_of(input, TERMINATOR); j++) {
/* Error here: will never be TRUE */
if (j == last_index_of) {
/* ... */
}
else {
/* ... */
}
}
would become:
int last_index = last_index_of(input, TERMINATOR);
for (int j = 0; j < last_index; j++) {
if (j == last_index) {
/* ... */
}
else {
/* ... */
}
}
Another problem, you use number variable without initializing it, you should write int number = 0 instead of int number;
After that, there is also a problem with your logic.
You have some idea of what you want to do, but it is not clear in your code.
It seems that you want
the user to input some string in the form 10010.100111
to split this string into two parts 10010 and 100111
to convert the first part into integer part 10010 -> 18
to convert the second part into fractional part 100111 -> 0.609...
This decomposition may lead you to write this kind of code:
#include "stdio.h"
#include "string.h"
#define MAX_BITS 32
#define MAX_LENGTH 49
//Code to find the index of where the string ends
int last_index_of(char in_str[], char ch)
{
int ret = 0;
for (int i = 0; i < MAX_LENGTH; i++) {
if (in_str[i] == ch) {
ret = i;
}
}
return ret;
}
void sub_string(char in_str[], char out_str[], int start, int end)
{
int i = 0;
while (start != end) {
/* warning, bounds are still not tested... */
out_str[i++] = in_str[start++];
}
out_str[i] = '\0';
}
void split(char *input, char *first, char *second)
{
int idx = last_index_of(input, '.');
sub_string(input, first, 0, idx);
sub_string(input, second, idx + 1, strlen(input));
}
int main()
{
//Declaration of variable
char input[MAX_LENGTH + 1]; // +1 for '\0'
char first[MAX_BITS];
char second[MAX_BITS];
/* Input from the user */
printf("Enter a floating point value in binary: ");
scanf("%s", input);
/* split integer and fractionnal parts */
split(input, first, second);
/* decode integer part */
printf("integer part:\n");
for (int i = strlen(first) - 1, j = 1; i > -1; --i, j <<= 1) {
if (first[i] == '1') {
printf("%d ", j);
}
}
/* decode frac part */
printf("\nfractionnal part:\n");
for (int i = 0; i < strlen(second); ++i) {
if (second[i] == '1') {
printf("1/%d ", 2 << i);
}
}
return 0;
}

convert each digit of a decimal number to correcsponding binary

I need to convert the string "12345678" to the value 00010010001101000101011001111000 (the value in binary only without the zeroes on the left).
So I have written this code in c, the problem is that when I run it does nothing, just waits like there is an error until I stop it manually.
Any ideas?
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[4], result[4*strlen(string)];
for (i=0; i<strlen(string); i++) {
num = atoi(string[i]);
while (num != 0) {
arr[j++] = num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = 0;
tmp--;
}
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k++] = arr[j--];
}
j = 0;
tmp = 4;
}
printf("The result is: \n");
for (i=0; i<4*strlen(result); i++) {
printf("%d",result[i]);
}
printf("\n");
}
int main() {
char c[8] = "12345678";
reduce(c);
return 0;
}
Lots of small errors in your code, which makes it hard to pin-point a single error. Main problem seems to be you are confusing binary numbers (0, 1) with ASCII digits ("0", "1") and are mis-using string functions.
as mentioned elsewhere, char c[8] = .. is wrong.
atoi(string[i]) cannot work; it expects a string, not a char. Use `num = string[i]-'0';
arr[..] gets the value 'num%2, that is, a numerical value. Better to use '0'+num%2 so it's a character string.
you increment k in result[k++] inside a loop that already increments k
add result[k] = 0; at the end before printing, so strlen works correctly
4*strlen(result) is way too much -- the strlen is what it is.
you might as well do a simple printf("%s\n", result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, tmp=4, num;
char arr[5], result[4*strlen(string)+1];
for (i=0; i<strlen(string); i++) {
num = string[i]-'0';
while (num != 0) {
arr[j++] = '0'+num%2;
num = num/2;
tmp--;
}
while (tmp != 0) {
arr[j++] = '0';
tmp--;
}
arr[j] = 0;
j--;
for (k=i*4; k<(i*4+4); k++) {
result[k] = arr[j--];
}
j = 0;
tmp = 4;
}
result[k] = 0;
printf("The result is: \n");
for (i=0; i<strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
}
int main() {
char c[] = "12345678";
reduce(c);
return 0;
}
.. resulting in
The result is:
00010010001101000101011001111000
It seems from your example that the conversion you are attempting is to binary coded decimal rather than binary. That being the case your solution is somewhat over-complicated; you simply need to convert each digit to its integer value then translate the bit pattern to ASCII 1's and 0's.
#include <stdio.h>
void reduce( const char* c )
{
for( int d = 0; c[d] != 0; d++ )
{
int ci = c[d] - '0' ;
for( unsigned mask = 0x8; mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
}
On the other hand if you did intend a conversion to binary (rather than BCD), then if the entire string is converted to an integer, you can directly translate the bit pattern to ASCII 1's and 0's as follows:
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
void reduce( const char* c )
{
unsigned ci = (unsigned)atoi( c ) ;
static const int BITS = sizeof(ci) * CHAR_BIT ;
for( unsigned mask = 0x01 << (BITS - 1); mask != 0; mask >>= 1 )
{
putchar( (ci & mask) == 0 ? '0' : '1' ) ;
}
}
In your main(), do either
char c[ ] = "12345678";
or
char c[9] = "12345678";
if you want to use c as a string. Otherwise, it does not have enough space to store the terminating null character.
Here, I took the liberty to modify the code accordingly to work for you. Check the below code. Hope it's self-explanatoty.
#include <stdio.h>
#include <string.h>
void reduce(char string[]) {
int i=0, j=0, k=0, cnt=0, count = 0; //count added, tmp removed
char arr[4], result[ (4*strlen(string) )+ 1], c; //1 more byte space to hold null
for (i=0; i<strlen(string); i++) {
c = string[i];
count = 4;
while (count != 0) { //constant iteration 4 times baed on 9 = 1001
arr[j++] = '0' + (c%2); //to store ASCII 0 or 1 [48/ 49]
c = c/2;
count--;
}
/* //not required
while (tmp >= 0) {
arr[j++] = 0;
tmp--;
}
*/
j--;
for (k=(i*4); k<((i*4) +4); k++) {
result[k] = arr[j--];
}
j = 0;
memset (arr, 0, sizeof(arr));
}
result[k] = 0;
printf("The result is: %s\n", result); //why to loop when we've added the terminating null? print directly.
/*
for (i=0; i< strlen(result); i++) {
printf("%c",result[i]);
}
printf("\n");
*/
}
int main() {
char c[ ] = "12345678";
reduce(c);
return 0;
}
Output:
[sourav#broadsword temp]$ ./a.out
The result is: 00010010001101000101011001111000
Convert your string to an integer using int num = atoi(c).
Then do
int binary[50];
int q = num,i=0;
while(q != 0)
{
binary[i++] = q%2;
q = q/2;
}
Printing your binary array is reverse order will have your binary equivalent.
Full program:
#include<stdio.h>
int main(){
char c[100];
int num,q;
int binary[100],i=0,j;
scanf("%d",c);
num = atoi(c);
q = num;
while(q!=0){
binary[i++]= q % 2;
q = q / 2;
}
for(j = i -1 ;j>= 0;j--)
printf("%d",binary[j]);
return 0;
}
You can use the below reduce function.
void reduce(char string[])
{
unsigned int in = atoi(string) ;
int i = 0, result[32],k,j;
while (in > 0) {
j = in % 10;
k = 0;
while (j > 0) {
result[i++] = j % 2;
j = j >> 1;
k++;
}
while (k < 4) {
result[i++] = 0;
k++;
}
in = in/10;
}
printf("Result\n");
for(--i;i >= 0; i--) {
printf("%d", result[i]);
}
printf("\n");
}
For 12345678
the output would be 00010010001101000101011001111000, where each character is printed in its binary format.
It might need some adjustments, but it does the job as it is.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int i;
int n;
char *str = "12345678";
const int bit = 1 << (sizeof(n)*8 - 1);
n = atoi(str);
for(i=0; i < sizeof(n)*8 ; i++, n <<= 1)
n&bit ? printf("1") : printf("0");
return 0;
}

Is there any simple way to add a prefix to each element of an array in C?

I'm solving gray code problem.
I made my logic using recursive call.
Everything look ok but I have no idea how to prefix '0' or '1' to each element of an array.
eg) prefix 0 : { 00, 01, 11, 10 } -> { 000, 001, 011, 010 } or
prefix 1 : { 00, 01, 11, 10 } -> { 100, 101, 111, 110 }
#include<stdio.h>
#include<string.h>
#include<math.h>
int grayCode(int list[], int bit)
{
int listLen = strlen(list); // calculate received array length
int revList[] = { 0 };
int newList[] = { 0 };
if (listLen < pow(2, bit)) // If the received array length is below 2^bit, proceed below.
{
for (int i = 0; i < listLen; i++) // create a reverse order array
{
revList[i] = list[listLen - i];
}
for (int i = 0; i < listLen; i++) // prefix 0 to each element of an received array, I know this doesn't work. How should I do it??
{
list[i] = "0" + list[i];
}
for (int i = 0; i < listLen; i++) // prefix 1 to each element of an reverse array, I know this doesn't work. How should I do it??
{
revList[i] = "1" + revList[i];
}
for (int i = 0; i < listLen; i++) // put all elements of received array in the new array
{
newList[i] = list[i];
}
for (int i = 0; i < listLen; i++) // put all elements of reverse array in the new array
{
newList[listLen + i] = revList[i];
}
for (int i = 0; i < listLen * 2; i++) // print all elements in a new array
{
printf("%d bit Gray Code is { ", bit);
printf("%d, ", newList[i]);
printf("}\n");
}
grayCode(newList, bit); // Recursive call
}
else if (listLen == pow(2, bit)) // If the received array length is same as 2^bit, return.
{
return 0;
}
}
int main(void)
{
int initList[2] = { 0, 1 };
int bit;
printf("Which bit of gray-code do you want? : ");
scanf_s("%d", &bit);
while (bit < 1)
{
printf("Input an integer bigger than 1 : ");
scanf_s("%d", &bit);
}
if (bit == 1)
{
printf("1 bit Gray Code is { 0, 1 }\n");
}
else if (bit > 1)
{
grayCode(initList, bit);
}
return 0;
}
No, you can't append 0 as prefix to an integer.
An integer starting with 0 is assumed as octal representation of corresponding decimal integer, i.e.:
(037)8 == (31)10
If you really want to save the numbers with prefixed 0s, you will have to store the numbers as strings.
You can use a temporary string for storing intermediates.
The algorithm will be:
char str[10] = "01"; // To be converted to 001
char temp[10];
strcpy(temp, "0"); // temp = "0", str = "01"
strcat(temp, str); // temp = "001", str = "01"
strcpy(str, temp); // temp = "001", str = "001"

Resources