I'm trying to read txt file (has numeric values) line by line.
I used SPIFFS and I used this function
void readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("− failed to open file for reading");
return;
}
int count = 0;
Serial.println(" read from file:");
while(file.available()){
if (count < 100)
Serial.write(file.read());
}
}
What is the alternative function for "file.read()" something like "readline" because I need to read the file from first line to 100 and from 101 to 200 and so on .
You need to use readStringUntil. Although it's not the most efficient way, i'll show you how it's done.
#include <vector>
#include <SPIFFS.h>
std::vector<double> readLine(String path, uint16_t from, uint16_t to) {
std::vector<double> list;
if(from > to) return list;
File file = SPIFFS.open(path.c_str());
if(!file) return list;
uint16_t counter = 0;
while(file.available() && counter <= to) {
counter++;
if(counter < from) {
file.readStringUntil('\n');
} else {
String data = file.readStringUntil('\n');
list.push_back(data.toDouble());
}
}
return list;
}
void setup() {
Serial.begin(115200);
SPIFFS.begin(true);
std::vector<double> numbers = readLine("file.txt", 0, 100);
Serial.println("Data from 0 to 100:");
uint16_t counter = 0;
for (auto& n : numbers) {
counter++;
Serial.print(String(n) + "\t");
if(counter % 10 == 0) {
Serial.println();
}
}
numbers = readLine("file.txt", 101, 200);
Serial.println("\nData from 101 to 200:");
counter = 0;
for (auto& n : numbers) {
counter++;
Serial.print(String(n) + "\t");
if(counter % 10 == 0) {
Serial.println();
}
}
}
UPDATE
Supposed you have 1050 values and you want to parse it for each 100 values.
int i = 0;
while(i < 1050) {
int start = i + 1;
int end = (i + 100) > 1050 ? 1050 : i + 100;
std::vector<double> numbers = readLine("file.txt", start, end);
Serial.println("Data from " + String(start) + " to " + String(end) + ":");
uint16_t counter = 0;
for (auto& n : numbers) {
counter++;
Serial.print(String(n) + "\t");
if(counter % 10 == 0) {
Serial.println();
}
}
i += 100;
}
To read lines from Serial, network Client, from File or other object implementing the Arduino Stream class you can use function readBytesUntil.
uint8_t lineBuffer[64];
while (file.available()) {
int length = file.readBytesUntil('\n', lineBuffer, sizeof(lineBuffer) - 1);
if (length > 0 && lineBuffer[length - 1] == '\r') {
length--; // to remove \r if it is there
}
lineBuffer[length] = 0; // terminate the string
Serial.println(lineBuffer);
}
The File is a Stream and has all of the methods that a Stream does, including readBytesUntil and readStringUntil.
I am currently experiencing bizarre results in my C program, where inside a for-loop, the variable hex_index increases at every line by 2. It's not time-related or anything. Still, it just increases by every line even though the statements have no relation to it.
ascii.c
#include <stdio.h>
#include "types.h"
int
main ()
{
char *hex = "68747541";
char output[4];
hex_to_ascii(hex, output);
printf("%s", output);
return 0;
}
length.c
#include <stddef.h>
/// Returns the length of the passed string based on checking the content
/// with NULL or #\0 which end a string
int get_str_len(char *string)
{
int len = 0;
for (int i = 0; 1; i++)
{
if (string[i] == '\0' || string[i] == NULL) return len;
len++;
}
}
/// Returns the length of the passed hex string
int get_hex_len(char *hex)
{
return get_str_len(hex);
}
types.c
#include "types.h"
#include "length.h"
/// Removes inside a string all control chars and overwrites the passed string
void remove_control_chars(char* string)
{
int len = get_str_len(string);
char new_string[len];
int string_index = 0;
int i;
for (i = 0; i < len; i++, string_index++)
{
if (string[i] < 127 && string[i] > 31)
{
new_string[i] = string[string_index];
}
else string_index++;
}
len = get_str_len(new_string);
for (i = 0; i < len; i++)
{
string[i] = new_string[i];
}
string[i] = '\0';
}
/// Converts an hex number to an int
/// If an invalid character is inside the string it will return -1 (Control chars will be automatically removed)
/// #param str The string that should be converted
int hex_to_int(char *str)
{
remove_control_chars(str);
int str_len = get_str_len(str);
int sum = 0;
int multiplier = 1;
// Calculating the multiplier for the biggest number (num at index 0)
for (int i = 1; i < str_len; i++) multiplier *= 16;
// Adding the multiplied value to the sum and then diving by the base (16)
for (int i = 0; i < str_len; i++, multiplier /= 16)
{
char byte = str[i];
if (byte >= '0' && byte <= '9') sum += (byte - '0') * multiplier;
else if (byte >= 'A' && byte <='F') sum += (byte - 'A' + 10) * multiplier;
else if (byte >= 'a' && byte <='f') sum += (byte - 'a' + 10) * multiplier;
// Avoiding control characters
else if (byte < 31) return sum;
else return -1;
}
return sum;
}
bool valid_hex_char(char byte)
{
return byte >= '0' && byte <= '9' || byte >= 'A' && byte <= 'F' || byte >= 'a' && byte <= 'f';
}
/// Converts an hex number to an dual ascii character and returns it
/// #param hex The string that should be converted
char dual_hex_to_ascii(char *hex)
{
int value = hex_to_int(hex);
return (char) value;
}
/// Converts an hex number to an ascii string
/// #param hex The string that should be converted
/// #param output The initialised string which will be overwritten
void hex_to_ascii(char *hex, char *output)
{
char storage[2];
int len = get_hex_len(hex);
int i = 0;
for (int hex_index = 0; hex_index < len; hex_index += 2)
{
if (valid_hex_char(hex[hex_index]))
{
storage[0] = hex[hex_index];
if (valid_hex_char(hex[hex_index+1]))
{
storage[1] = hex[hex_index+1];
}
else
{
storage[1] = '\0';
}
output[i] = dual_hex_to_ascii(storage);
i++;
}
else
{
return;
}
}
}
Video to the issue (Watch hex_index, which will randomly increase)
I found the issue that caused this. The debugger had watches left that at every line re-evaluated the values calling the increment at every line. So the code is fine but I made a mistake inside the debugger session.
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);
}
}
A simple routine i wrote for converting ASCII string to corresponding 7-bit GSM coding scheme:
#include <stdio.h>
#include <process.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
/* convert ascii input string to 7-bit GSM alphabet */
bool ascii_to_gsm(const char* in, uint8_t len, uint8_t* out, uint8_t start_indx) {
if (in == NULL || out == NULL || len == 0)
return false;
uint8_t nshift = 7;
memcpy(out + start_indx, in, len);
for (size_t i = 0; i < len - 1; i++) {
nshift = (nshift == 255) ? 7 : nshift;
uint16_t l = out[start_indx + i];
uint16_t h = out[start_indx + i + 1];
h = (h << nshift--) | l;
out[start_indx + i] = h;
out[start_indx + i + 1] = h >> 8;
}
return true;
}
int main() {
char data[] = "ASCIIASCII";
uint8_t buff[sizeof(data) - 1];
memset(buff, 0, sizeof(buff));
ascii_to_gsm(data, sizeof(buff), buff, 0);
for (size_t i = 0; i < sizeof(buff); i++) {
printf("\n buff[%d]=%02x", i, buff[i]);
}
system("pause");
return 0;
}
For strings like ASCII or TEST it's working fine and output is C1E9309904 and D4E2940Arespectively.
But for string ASCIIASCII some output byte is wrong:
C1E930990C4E87498024
The result should be: C1E930990C4E87C924
Don't know what part, i'm wrong.
Concepts about GSM coding can be found here.
I use this online encoder to compare results
But for string ASCIIASCII some output byte is wrong:
C1E930990C4E87498024
The result should be:
C1E930990C4E87C924
OP's code does not take into account the output may have a shorter length than the input.
If the input is 10 ASCII characters, that is 70 bits. The output needs to be ceiling(70/8) or 9 bytes. Also see #Steve Summit.
A simplified code for reference that lacks a start_indx. Since input is a string ("converting ASCII string"), the input length is not needed.
bool ascii_to_gsmA(const char* in, uint8_t* out) {
unsigned bit_count = 0;
unsigned bit_queue = 0;
while (*in) {
bit_queue |= (*in & 0x7Fu) << bit_count;
bit_count += 7;
if (bit_count >= 8) {
*out++ = (uint8_t) bit_queue;
bit_count -= 8;
bit_queue >>= 8;
}
in++;
}
if (bit_count > 0) {
*out++ = (uint8_t) bit_queue;
}
return true;
}
I'm looking for a function to allow me to print the binary representation of an int. What I have so far is;
char *int2bin(int a)
{
char *str,*tmp;
int cnt = 31;
str = (char *) malloc(33); /*32 + 1 , because its a 32 bit bin number*/
tmp = str;
while ( cnt > -1 ){
str[cnt]= '0';
cnt --;
}
cnt = 31;
while (a > 0){
if (a%2==1){
str[cnt] = '1';
}
cnt--;
a = a/2 ;
}
return tmp;
}
But when I call
printf("a %s",int2bin(aMask)) // aMask = 0xFF000000
I get output like;
0000000000000000000000000000000000xtpYy (And a bunch of unknown characters.
Is it a flaw in the function or am I printing the address of the character array or something? Sorry, I just can't see where I'm going wrong.
NB The code is from here
EDIT: It's not homework FYI, I'm trying to debug someone else's image manipulation routines in an unfamiliar language. If however it's been tagged as homework because it's an elementary concept then fair play.
Here's another option that is more optimized where you pass in your allocated buffer. Make sure it's the correct size.
// buffer must have length >= sizeof(int) + 1
// Write to the buffer backwards so that the binary representation
// is in the correct order i.e. the LSB is on the far right
// instead of the far left of the printed string
char *int2bin(int a, char *buffer, int buf_size) {
buffer += (buf_size - 1);
for (int i = 31; i >= 0; i--) {
*buffer-- = (a & 1) + '0';
a >>= 1;
}
return buffer;
}
#define BUF_SIZE 33
int main() {
char buffer[BUF_SIZE];
buffer[BUF_SIZE - 1] = '\0';
int2bin(0xFF000000, buffer, BUF_SIZE - 1);
printf("a = %s", buffer);
}
A few suggestions:
null-terminate your string
don't use magic numbers
check the return value of malloc()
don't cast the return value of malloc()
use binary operations instead of arithmetic ones as you're interested in the binary representation
there's no need for looping twice
Here's the code:
#include <stdlib.h>
#include <limits.h>
char * int2bin(int i)
{
size_t bits = sizeof(int) * CHAR_BIT;
char * str = malloc(bits + 1);
if(!str) return NULL;
str[bits] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *)&i;
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
return str;
}
Your string isn't null-terminated. Make sure you add a '\0' character at the end of the string; or, you could allocate it with calloc instead of malloc, which will zero the memory that is returned to you.
By the way, there are other problems with this code:
As used, it allocates memory when you call it, leaving the caller responsible for free()ing the allocated string. You'll leak memory if you just call it in a printf call.
It makes two passes over the number, which is unnecessary. You can do everything in one loop.
Here's an alternative implementation you could use.
#include <stdlib.h>
#include <limits.h>
char *int2bin(unsigned n, char *buf)
{
#define BITS (sizeof(n) * CHAR_BIT)
static char static_buf[BITS + 1];
int i;
if (buf == NULL)
buf = static_buf;
for (i = BITS - 1; i >= 0; --i) {
buf[i] = (n & 1) ? '1' : '0';
n >>= 1;
}
buf[BITS] = '\0';
return buf;
#undef BITS
}
Usage:
printf("%s\n", int2bin(0xFF00000000, NULL));
The second parameter is a pointer to a buffer you want to store the result string in. If you don't have a buffer you can pass NULL and int2bin will write to a static buffer and return that to you. The advantage of this over the original implementation is that the caller doesn't have to worry about free()ing the string that gets returned.
A downside is that there's only one static buffer so subsequent calls will overwrite the results from previous calls. You couldn't save the results from multiple calls for later use. Also, it is not threadsafe, meaning if you call the function this way from different threads they could clobber each other's strings. If that's a possibility you'll need to pass in your own buffer instead of passing NULL, like so:
char str[33];
int2bin(0xDEADBEEF, str);
puts(str);
Here is a simple algorithm.
void decimalToBinary (int num) {
//Initialize mask
unsigned int mask = 0x80000000;
size_t bits = sizeof(num) * CHAR_BIT;
for (int count = 0 ;count < bits; count++) {
//print
(mask & num ) ? cout <<"1" : cout <<"0";
//shift one to the right
mask = mask >> 1;
}
}
this is what i made to display an interger as a binairy code it is separated per 4 bits:
int getal = 32; /** To determain the value of a bit 2^i , intergers are 32bits long**/
int binairy[getal]; /** A interger array to put the bits in **/
int i; /** Used in the for loop **/
for(i = 0; i < 32; i++)
{
binairy[i] = (integer >> (getal - i) - 1) & 1;
}
int a , counter = 0;
for(a = 0;a<32;a++)
{
if (counter == 4)
{
counter = 0;
printf(" ");
}
printf("%i", binairy[a]);
teller++;
}
it could be a bit big but i always write it in a way (i hope) that everyone can understand what is going on. hope this helped.
#include<stdio.h>
//#include<conio.h> // use this if you are running your code in visual c++, linux don't
// have this library. i have used it for getch() to hold the screen for input char.
void showbits(int);
int main()
{
int no;
printf("\nEnter number to convert in binary\n");
scanf("%d",&no);
showbits(no);
// getch(); // used to hold screen...
// keep code as it is if using gcc. if using windows uncomment #include & getch()
return 0;
}
void showbits(int n)
{
int i,k,andmask;
for(i=15;i>=0;i--)
{
andmask = 1 << i;
k = n & andmask;
k == 0 ? printf("0") : printf("1");
}
}
Just a enhance of the answer from #Adam Markowitz
To let the function support uint8 uint16 uint32 and uint64:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
// Convert integer number to binary representation.
// The buffer must have bits bytes length.
void int2bin(uint64_t number, uint8_t *buffer, int bits) {
memset(buffer, '0', bits);
buffer += bits - 1;
for (int i = bits - 1; i >= 0; i--) {
*buffer-- = (number & 1) + '0';
number >>= 1;
}
}
int main(int argc, char *argv[]) {
char buffer[65];
buffer[8] = '\0';
int2bin(1234567890123, buffer, 8);
printf("1234567890123 in 8 bits: %s\n", buffer);
buffer[16] = '\0';
int2bin(1234567890123, buffer, 16);
printf("1234567890123 in 16 bits: %s\n", buffer);
buffer[32] = '\0';
int2bin(1234567890123, buffer, 32);
printf("1234567890123 in 32 bits: %s\n", buffer);
buffer[64] = '\0';
int2bin(1234567890123, buffer, 64);
printf("1234567890123 in 64 bits: %s\n", buffer);
return 0;
}
The output:
1234567890123 in 8 bits: 11001011
1234567890123 in 16 bits: 0000010011001011
1234567890123 in 32 bits: 01110001111110110000010011001011
1234567890123 in 64 bits: 0000000000000000000000010001111101110001111110110000010011001011
Two things:
Where do you put the NUL character? I can't see a place where '\0' is set.
Int is signed, and 0xFF000000 would be interpreted as a negative value. So while (a > 0) will be false immediately.
Aside: The malloc function inside is ugly. What about providing a buffer to int2bin?
A couple of things:
int f = 32;
int i = 1;
do{
str[--f] = i^a?'1':'0';
}while(i<<1);
It's highly platform dependent, but
maybe this idea above gets you started.
Why not use memset(str, 0, 33) to set
the whole char array to 0?
Don't forget to free()!!! the char*
array after your function call!
Two simple versions coded here (reproduced with mild reformatting).
#include <stdio.h>
/* Print n as a binary number */
void printbitssimple(int n)
{
unsigned int i;
i = 1<<(sizeof(n) * 8 - 1);
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
/* Print n as a binary number */
void printbits(int n)
{
unsigned int i, step;
if (0 == n) /* For simplicity's sake, I treat 0 as a special case*/
{
printf("0000");
return;
}
i = 1<<(sizeof(n) * 8 - 1);
step = -1; /* Only print the relevant digits */
step >>= 4; /* In groups of 4 */
while (step >= n)
{
i >>= 4;
step >>= 4;
}
/* At this point, i is the smallest power of two larger or equal to n */
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 32; ++i)
{
printf("%d = ", i);
//printbitssimple(i);
printbits(i);
printf("\n");
}
return 0;
}
//This is what i did when our teacher asked us to do this
int main (int argc, char *argv[]) {
int number, i, size, mask; // our input,the counter,sizeofint,out mask
size = sizeof(int);
mask = 1<<(size*8-1);
printf("Enter integer: ");
scanf("%d", &number);
printf("Integer is :\t%d 0x%X\n", number, number);
printf("Bin format :\t");
for(i=0 ; i<size*8 ;++i ) {
if ((i % 4 == 0) && (i != 0)) {
printf(" ");
}
printf("%u",number&mask ? 1 : 0);
number = number<<1;
}
printf("\n");
return (0);
}
the simplest way for me doing this (for a 8bit representation):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *intToBinary(int z, int bit_length){
int div;
int counter = 0;
int counter_length = (int)pow(2, bit_length);
char *bin_str = calloc(bit_length, sizeof(char));
for (int i=counter_length; i > 1; i=i/2, counter++) {
div = z % i;
div = div / (i / 2);
sprintf(&bin_str[counter], "%i", div);
}
return bin_str;
}
int main(int argc, const char * argv[]) {
for (int i = 0; i < 256; i++) {
printf("%s\n", intToBinary(i, 8)); //8bit but you could do 16 bit as well
}
return 0;
}
Here is another solution that does not require a char *.
#include <stdio.h>
#include <stdlib.h>
void print_int(int i)
{
int j = -1;
while (++j < 32)
putchar(i & (1 << j) ? '1' : '0');
putchar('\n');
}
int main(void)
{
int i = -1;
while (i < 6)
print_int(i++);
return (0);
}
Or here for more readability:
#define GRN "\x1B[32;1m"
#define NRM "\x1B[0m"
void print_int(int i)
{
int j = -1;
while (++j < 32)
{
if (i & (1 << j))
printf(GRN "1");
else
printf(NRM "0");
}
putchar('\n');
}
And here is the output:
11111111111111111111111111111111
00000000000000000000000000000000
10000000000000000000000000000000
01000000000000000000000000000000
11000000000000000000000000000000
00100000000000000000000000000000
10100000000000000000000000000000
#include <stdio.h>
#define BITS_SIZE 8
void
int2Bin ( int a )
{
int i = BITS_SIZE - 1;
/*
* Tests each bit and prints; starts with
* the MSB
*/
for ( i; i >= 0; i-- )
{
( a & 1 << i ) ? printf ( "1" ) : printf ( "0" );
}
return;
}
int
main ()
{
int d = 5;
printf ( "Decinal: %d\n", d );
printf ( "Binary: " );
int2Bin ( d );
printf ( "\n" );
return 0;
}
Not so elegant, but accomplishes your goal and it is very easy to understand:
#include<stdio.h>
int binario(int x, int bits)
{
int matriz[bits];
int resto=0,i=0;
float rest =0.0 ;
for(int i=0;i<8;i++)
{
resto = x/2;
rest = x%2;
x = resto;
if (rest>0)
{
matriz[i]=1;
}
else matriz[i]=0;
}
for(int j=bits-1;j>=0;j--)
{
printf("%d",matriz[j]);
}
printf("\n");
}
int main()
{
int num,bits;
bits = 8;
for (int i = 0; i < 256; i++)
{
num = binario(i,bits);
}
return 0;
}
#include <stdio.h>
int main(void) {
int a,i,k=1;
int arr[32]; \\ taken an array of size 32
for(i=0;i <32;i++)
{
arr[i] = 0; \\initialised array elements to zero
}
printf("enter a number\n");
scanf("%d",&a); \\get input from the user
for(i = 0;i < 32 ;i++)
{
if(a&k) \\bit wise and operation
{
arr[i]=1;
}
else
{
arr[i]=0;
}
k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
printf("%d",arr[i]); \\print the array in reverse
}
return 0;
}
void print_binary(int n) {
if (n == 0 || n ==1)
cout << n;
else {
print_binary(n >> 1);
cout << (n & 0x1);
}
}