Convert decimal to binary
This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.
#include <stdio.h>
#include <string.h>
void print_out_reversed(char string)
{
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
putchar('n');
}
void print_decimal_number_binary(int number)
{
if (number == 0)
{
printf("0n");
return;
}
char bits[sizeof(int) * 8 + 1] = {0};
int index = 0;
while (number > 0)
{
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
number = number / 2;
index++;
}
print_out_reversed(bits);
}
int main()
{
printf("enter number: ");
int number;
scanf("%i", &number);
print_decimal_number_binary(number);
}
beginner c number-systems
New contributor
add a comment |
This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.
#include <stdio.h>
#include <string.h>
void print_out_reversed(char string)
{
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
putchar('n');
}
void print_decimal_number_binary(int number)
{
if (number == 0)
{
printf("0n");
return;
}
char bits[sizeof(int) * 8 + 1] = {0};
int index = 0;
while (number > 0)
{
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
number = number / 2;
index++;
}
print_out_reversed(bits);
}
int main()
{
printf("enter number: ");
int number;
scanf("%i", &number);
print_decimal_number_binary(number);
}
beginner c number-systems
New contributor
add a comment |
This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.
#include <stdio.h>
#include <string.h>
void print_out_reversed(char string)
{
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
putchar('n');
}
void print_decimal_number_binary(int number)
{
if (number == 0)
{
printf("0n");
return;
}
char bits[sizeof(int) * 8 + 1] = {0};
int index = 0;
while (number > 0)
{
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
number = number / 2;
index++;
}
print_out_reversed(bits);
}
int main()
{
printf("enter number: ");
int number;
scanf("%i", &number);
print_decimal_number_binary(number);
}
beginner c number-systems
New contributor
This program converts a decimal number to a binary number. This is one of my first C programs and I am wondering if I have used the elements of this language properly. Suggestions for improvement are welcome.
#include <stdio.h>
#include <string.h>
void print_out_reversed(char string)
{
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
putchar('n');
}
void print_decimal_number_binary(int number)
{
if (number == 0)
{
printf("0n");
return;
}
char bits[sizeof(int) * 8 + 1] = {0};
int index = 0;
while (number > 0)
{
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
number = number / 2;
index++;
}
print_out_reversed(bits);
}
int main()
{
printf("enter number: ");
int number;
scanf("%i", &number);
print_decimal_number_binary(number);
}
beginner c number-systems
beginner c number-systems
New contributor
New contributor
edited yesterday
200_success
128k15152413
128k15152413
New contributor
asked yesterday
Vengeancos
684
684
New contributor
New contributor
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
Terminology
It's important to be able to understand (and describe) what's actually going on. Your program
- converts from an integer decimal string representation to an integer using
scanf
. This integer is then represented as a binary number in the processor. - converts from that integer back into a string representation, but rather than it being decimal, it's binary.
So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".
Use const
void print_out_reversed(char string)
doesn't modify string
, so write const char string
.
Simplify your strlen
usage
This:
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
can be
for (int i = strlen(string)-1; i >= 0; i--)
putchar(string[i]);
It seems that you don't trust what strlen
is doing, which is why you have that intermediate while
loop. But that loop won't have any effect, because the null terminator will always be where strlen
says it is.
Use math instead of if
This:
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
can be
bits[index] = '0' + (number & 1);
Use combined operation and assignment
This:
number = number / 2;
should be
number /= 2;
or, for speed (which the compiler will do for you anyway)
number >>= 1;
add a comment |
#include <stdio.h>
void get_bits(void * num, char * out, int bytes);
int main(void)
{
int x = 0;
printf("Enter an integer: ");
scanf("%i", &x);
char bits[65] = {0};//length of 65 here, but only need length of 33
get_bits(&x, bits, 4);
printf("%d in binary %sn", x, bits);
return 0;
}
//assumes char array of length 1 greater than
//number of bits
//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN
void get_bits(void * num, char *out, int bytes)
{
unsigned long long filter = 0x8000000000000000;
unsigned long long *temp = num;
if(bytes <= 0) return;
if(bytes > 8) bytes = 8;
filter = filter >> (8*(sizeof(unsigned long long)-bytes));
//memcpy(&temp, num, bytes);
int bits = 8*bytes;
for(int i=0;i<bits;i++) {
//if(filter & temp)
if((filter >> i) & *temp)
out[i] = '1';
else
out[i] = '0';
//temp = temp << 1;
}
out[bits] = '';
}
EDIT
Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.
Improvements
The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.
The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).
One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.
Alternative Solution
The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).
It will "return," really populate, a character array with up to a 64-bit bit representation of the number.
It NO LONGER relies on memcpy from string.h.
Inputs for get_bits
void *num : a pointer to the memory address of the number to be represented in
binary
char *out : the address of a character array to store the bit representation.
NOTE: This should be of length 1 longer than the number of bits to
be represented
int bytes : number of bytes containing the number to represent in binary
Implementation
Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number, as a void*, is effectively cast to a pointer to unsigned long long a stored in temp. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.
Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.
Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.
At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.
Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)
New contributor
Why would you makebits
a 64-character string if you're only scanning a 32-bit integer?
– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
|
show 3 more comments
I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.
Here's the code; it's quite simple:
#include <stdint.h>
#include <stdio.h>
static void printBinary(const uint8_t *restrict num, int bytes) {
for (int p = bytes - 1; p >= 0; p--) {
uint8_t x = num[p];
for (int i = 0; i < 8; i++) {
putchar('0' | (x >> 7));
x <<= 1;
}
}
}
int main() {
int64_t x;
for (;;) {
puts("Enter an integer: ");
if (scanf("%lld", &x) == 1)
break;
while (getchar() != 'n');
}
printBinary((uint8_t*)&x, sizeof(x));
putchar('n');
return 0;
}
Things to observe as compared to the OP's code (and RJM's code):
- There are no calls to
malloc
ormemcpy
. - The result is not stored in memory; it's output directly to
stdout
. - The input integer has a primitive form of validation. The program will loop until
scanf
succeeds. - The input integer supports 64 bits instead of 32.
- The output routine supports integers of any length, with the assumption that the integer is little-endian.
- The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.
- There is no need for a "filter" (mask) variable.
- The main loop does not need an
if
.
I'm happy to explain any aspect of this approach for the purposes of education.
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
add a comment |
// Sergio's
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary(unsigned number)
{
if (number > 1)
binary(number/2);
printf("%d", number % 2);
}
int main(void)
{
int value=10;
binary(value);
return 0;
}
New contributor
We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210909%2fconvert-decimal-to-binary%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Terminology
It's important to be able to understand (and describe) what's actually going on. Your program
- converts from an integer decimal string representation to an integer using
scanf
. This integer is then represented as a binary number in the processor. - converts from that integer back into a string representation, but rather than it being decimal, it's binary.
So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".
Use const
void print_out_reversed(char string)
doesn't modify string
, so write const char string
.
Simplify your strlen
usage
This:
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
can be
for (int i = strlen(string)-1; i >= 0; i--)
putchar(string[i]);
It seems that you don't trust what strlen
is doing, which is why you have that intermediate while
loop. But that loop won't have any effect, because the null terminator will always be where strlen
says it is.
Use math instead of if
This:
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
can be
bits[index] = '0' + (number & 1);
Use combined operation and assignment
This:
number = number / 2;
should be
number /= 2;
or, for speed (which the compiler will do for you anyway)
number >>= 1;
add a comment |
Terminology
It's important to be able to understand (and describe) what's actually going on. Your program
- converts from an integer decimal string representation to an integer using
scanf
. This integer is then represented as a binary number in the processor. - converts from that integer back into a string representation, but rather than it being decimal, it's binary.
So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".
Use const
void print_out_reversed(char string)
doesn't modify string
, so write const char string
.
Simplify your strlen
usage
This:
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
can be
for (int i = strlen(string)-1; i >= 0; i--)
putchar(string[i]);
It seems that you don't trust what strlen
is doing, which is why you have that intermediate while
loop. But that loop won't have any effect, because the null terminator will always be where strlen
says it is.
Use math instead of if
This:
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
can be
bits[index] = '0' + (number & 1);
Use combined operation and assignment
This:
number = number / 2;
should be
number /= 2;
or, for speed (which the compiler will do for you anyway)
number >>= 1;
add a comment |
Terminology
It's important to be able to understand (and describe) what's actually going on. Your program
- converts from an integer decimal string representation to an integer using
scanf
. This integer is then represented as a binary number in the processor. - converts from that integer back into a string representation, but rather than it being decimal, it's binary.
So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".
Use const
void print_out_reversed(char string)
doesn't modify string
, so write const char string
.
Simplify your strlen
usage
This:
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
can be
for (int i = strlen(string)-1; i >= 0; i--)
putchar(string[i]);
It seems that you don't trust what strlen
is doing, which is why you have that intermediate while
loop. But that loop won't have any effect, because the null terminator will always be where strlen
says it is.
Use math instead of if
This:
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
can be
bits[index] = '0' + (number & 1);
Use combined operation and assignment
This:
number = number / 2;
should be
number /= 2;
or, for speed (which the compiler will do for you anyway)
number >>= 1;
Terminology
It's important to be able to understand (and describe) what's actually going on. Your program
- converts from an integer decimal string representation to an integer using
scanf
. This integer is then represented as a binary number in the processor. - converts from that integer back into a string representation, but rather than it being decimal, it's binary.
So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".
Use const
void print_out_reversed(char string)
doesn't modify string
, so write const char string
.
Simplify your strlen
usage
This:
int index = strlen(string);
while (string[index] != '')
index--;
for (int i = index; i >= 0; i--)
putchar(string[i]);
can be
for (int i = strlen(string)-1; i >= 0; i--)
putchar(string[i]);
It seems that you don't trust what strlen
is doing, which is why you have that intermediate while
loop. But that loop won't have any effect, because the null terminator will always be where strlen
says it is.
Use math instead of if
This:
if (number % 2 == 0)
{
bits[index] = '0';
}
else
{
bits[index] = '1';
}
can be
bits[index] = '0' + (number & 1);
Use combined operation and assignment
This:
number = number / 2;
should be
number /= 2;
or, for speed (which the compiler will do for you anyway)
number >>= 1;
answered yesterday
Reinderien
3,842821
3,842821
add a comment |
add a comment |
#include <stdio.h>
void get_bits(void * num, char * out, int bytes);
int main(void)
{
int x = 0;
printf("Enter an integer: ");
scanf("%i", &x);
char bits[65] = {0};//length of 65 here, but only need length of 33
get_bits(&x, bits, 4);
printf("%d in binary %sn", x, bits);
return 0;
}
//assumes char array of length 1 greater than
//number of bits
//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN
void get_bits(void * num, char *out, int bytes)
{
unsigned long long filter = 0x8000000000000000;
unsigned long long *temp = num;
if(bytes <= 0) return;
if(bytes > 8) bytes = 8;
filter = filter >> (8*(sizeof(unsigned long long)-bytes));
//memcpy(&temp, num, bytes);
int bits = 8*bytes;
for(int i=0;i<bits;i++) {
//if(filter & temp)
if((filter >> i) & *temp)
out[i] = '1';
else
out[i] = '0';
//temp = temp << 1;
}
out[bits] = '';
}
EDIT
Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.
Improvements
The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.
The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).
One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.
Alternative Solution
The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).
It will "return," really populate, a character array with up to a 64-bit bit representation of the number.
It NO LONGER relies on memcpy from string.h.
Inputs for get_bits
void *num : a pointer to the memory address of the number to be represented in
binary
char *out : the address of a character array to store the bit representation.
NOTE: This should be of length 1 longer than the number of bits to
be represented
int bytes : number of bytes containing the number to represent in binary
Implementation
Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number, as a void*, is effectively cast to a pointer to unsigned long long a stored in temp. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.
Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.
Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.
At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.
Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)
New contributor
Why would you makebits
a 64-character string if you're only scanning a 32-bit integer?
– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
|
show 3 more comments
#include <stdio.h>
void get_bits(void * num, char * out, int bytes);
int main(void)
{
int x = 0;
printf("Enter an integer: ");
scanf("%i", &x);
char bits[65] = {0};//length of 65 here, but only need length of 33
get_bits(&x, bits, 4);
printf("%d in binary %sn", x, bits);
return 0;
}
//assumes char array of length 1 greater than
//number of bits
//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN
void get_bits(void * num, char *out, int bytes)
{
unsigned long long filter = 0x8000000000000000;
unsigned long long *temp = num;
if(bytes <= 0) return;
if(bytes > 8) bytes = 8;
filter = filter >> (8*(sizeof(unsigned long long)-bytes));
//memcpy(&temp, num, bytes);
int bits = 8*bytes;
for(int i=0;i<bits;i++) {
//if(filter & temp)
if((filter >> i) & *temp)
out[i] = '1';
else
out[i] = '0';
//temp = temp << 1;
}
out[bits] = '';
}
EDIT
Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.
Improvements
The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.
The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).
One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.
Alternative Solution
The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).
It will "return," really populate, a character array with up to a 64-bit bit representation of the number.
It NO LONGER relies on memcpy from string.h.
Inputs for get_bits
void *num : a pointer to the memory address of the number to be represented in
binary
char *out : the address of a character array to store the bit representation.
NOTE: This should be of length 1 longer than the number of bits to
be represented
int bytes : number of bytes containing the number to represent in binary
Implementation
Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number, as a void*, is effectively cast to a pointer to unsigned long long a stored in temp. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.
Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.
Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.
At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.
Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)
New contributor
Why would you makebits
a 64-character string if you're only scanning a 32-bit integer?
– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
|
show 3 more comments
#include <stdio.h>
void get_bits(void * num, char * out, int bytes);
int main(void)
{
int x = 0;
printf("Enter an integer: ");
scanf("%i", &x);
char bits[65] = {0};//length of 65 here, but only need length of 33
get_bits(&x, bits, 4);
printf("%d in binary %sn", x, bits);
return 0;
}
//assumes char array of length 1 greater than
//number of bits
//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN
void get_bits(void * num, char *out, int bytes)
{
unsigned long long filter = 0x8000000000000000;
unsigned long long *temp = num;
if(bytes <= 0) return;
if(bytes > 8) bytes = 8;
filter = filter >> (8*(sizeof(unsigned long long)-bytes));
//memcpy(&temp, num, bytes);
int bits = 8*bytes;
for(int i=0;i<bits;i++) {
//if(filter & temp)
if((filter >> i) & *temp)
out[i] = '1';
else
out[i] = '0';
//temp = temp << 1;
}
out[bits] = '';
}
EDIT
Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.
Improvements
The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.
The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).
One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.
Alternative Solution
The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).
It will "return," really populate, a character array with up to a 64-bit bit representation of the number.
It NO LONGER relies on memcpy from string.h.
Inputs for get_bits
void *num : a pointer to the memory address of the number to be represented in
binary
char *out : the address of a character array to store the bit representation.
NOTE: This should be of length 1 longer than the number of bits to
be represented
int bytes : number of bytes containing the number to represent in binary
Implementation
Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number, as a void*, is effectively cast to a pointer to unsigned long long a stored in temp. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.
Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.
Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.
At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.
Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)
New contributor
#include <stdio.h>
void get_bits(void * num, char * out, int bytes);
int main(void)
{
int x = 0;
printf("Enter an integer: ");
scanf("%i", &x);
char bits[65] = {0};//length of 65 here, but only need length of 33
get_bits(&x, bits, 4);
printf("%d in binary %sn", x, bits);
return 0;
}
//assumes char array of length 1 greater than
//number of bits
//EDIT: VERSION WITHOUT MEMCPY AS REMINDED BY @REINDERIEN
void get_bits(void * num, char *out, int bytes)
{
unsigned long long filter = 0x8000000000000000;
unsigned long long *temp = num;
if(bytes <= 0) return;
if(bytes > 8) bytes = 8;
filter = filter >> (8*(sizeof(unsigned long long)-bytes));
//memcpy(&temp, num, bytes);
int bits = 8*bytes;
for(int i=0;i<bits;i++) {
//if(filter & temp)
if((filter >> i) & *temp)
out[i] = '1';
else
out[i] = '0';
//temp = temp << 1;
}
out[bits] = '';
}
EDIT
Sorry, I just realized what Code Review meant. I figured I was suggesting an improvement, but I see how it did not match the intent here. Maybe this is closer.
Improvements
The posted code requires several loops, divisions, and modulus calculations. While it does solve the problem of representing an integer in binary, the utility may be limited by additional clock cycles.
The code may be optimized and extended to use with other integer representations, including char, short, or long long (or long depending on the size of long).
One drawback of the posted code is the need to reverse bits. Utilizing a mask to filter which bits are set in the number is more efficient.
Alternative Solution
The function get_bits will accept any integer representation (presumably floating-point numbers as well, though I have not used it for this and not tested it).
It will "return," really populate, a character array with up to a 64-bit bit representation of the number.
It NO LONGER relies on memcpy from string.h.
Inputs for get_bits
void *num : a pointer to the memory address of the number to be represented in
binary
char *out : the address of a character array to store the bit representation.
NOTE: This should be of length 1 longer than the number of bits to
be represented
int bytes : number of bytes containing the number to represent in binary
Implementation
Based on the size of the data type of the number to be represented, a mask is established with the highest bit set. This is the variable, filter, of type unsigned long long contained in 64-bits. The input number, as a void*, is effectively cast to a pointer to unsigned long long a stored in temp. Using bit shifting, a time requirement of 1 clock cycle, the filter is shifted to the right to align it with the highest bit of the number.
Ex. In hexadecimal, a 16-bit filter would be 0x8000, which in binary is 100000000000000.
Only a single for loop is performed to populate the output string. In each iteration of the loop, a bit-wise AND is performed with filter and *temp. The result of this expression is either 0 or non-zero. The result is 0 only, when the highest order bit of temp is 0. The position in the output string is set to 1 if non-zero or 0 otherwise.
At the end of each iteration the filter is shifted incrementally by 1 more bit to the right.
Ex. In binary, if temp is 1010, then temp << 1 is 0100. (a suitable filter would be 1000 in binary)
New contributor
edited 10 hours ago
New contributor
answered yesterday
RJM
1295
1295
New contributor
New contributor
Why would you makebits
a 64-character string if you're only scanning a 32-bit integer?
– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
|
show 3 more comments
Why would you makebits
a 64-character string if you're only scanning a 32-bit integer?
– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
Why would you make
bits
a 64-character string if you're only scanning a 32-bit integer?– Reinderien
16 hours ago
Why would you make
bits
a 64-character string if you're only scanning a 32-bit integer?– Reinderien
16 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien because this will work for numbers requiring 64 bits to represent. It will adjust down to the proper length according to the argument, bytes. If you passed it a char array of length 33, it would work, if bytes = 32.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. You could use unsigned int too, but you would not be able to get the bits for long long (64 bits). Better to memcpy to temp to avoid sign extension in arithmetic right shift.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
@reinderien. I used that to exemplify the possibility. x would have to be long long (or potentially long) for it to be pertinent. Not needed here for int.
– RJM
15 hours ago
1
1
Let us continue this discussion in chat.
– Reinderien
13 hours ago
Let us continue this discussion in chat.
– Reinderien
13 hours ago
|
show 3 more comments
I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.
Here's the code; it's quite simple:
#include <stdint.h>
#include <stdio.h>
static void printBinary(const uint8_t *restrict num, int bytes) {
for (int p = bytes - 1; p >= 0; p--) {
uint8_t x = num[p];
for (int i = 0; i < 8; i++) {
putchar('0' | (x >> 7));
x <<= 1;
}
}
}
int main() {
int64_t x;
for (;;) {
puts("Enter an integer: ");
if (scanf("%lld", &x) == 1)
break;
while (getchar() != 'n');
}
printBinary((uint8_t*)&x, sizeof(x));
putchar('n');
return 0;
}
Things to observe as compared to the OP's code (and RJM's code):
- There are no calls to
malloc
ormemcpy
. - The result is not stored in memory; it's output directly to
stdout
. - The input integer has a primitive form of validation. The program will loop until
scanf
succeeds. - The input integer supports 64 bits instead of 32.
- The output routine supports integers of any length, with the assumption that the integer is little-endian.
- The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.
- There is no need for a "filter" (mask) variable.
- The main loop does not need an
if
.
I'm happy to explain any aspect of this approach for the purposes of education.
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
add a comment |
I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.
Here's the code; it's quite simple:
#include <stdint.h>
#include <stdio.h>
static void printBinary(const uint8_t *restrict num, int bytes) {
for (int p = bytes - 1; p >= 0; p--) {
uint8_t x = num[p];
for (int i = 0; i < 8; i++) {
putchar('0' | (x >> 7));
x <<= 1;
}
}
}
int main() {
int64_t x;
for (;;) {
puts("Enter an integer: ");
if (scanf("%lld", &x) == 1)
break;
while (getchar() != 'n');
}
printBinary((uint8_t*)&x, sizeof(x));
putchar('n');
return 0;
}
Things to observe as compared to the OP's code (and RJM's code):
- There are no calls to
malloc
ormemcpy
. - The result is not stored in memory; it's output directly to
stdout
. - The input integer has a primitive form of validation. The program will loop until
scanf
succeeds. - The input integer supports 64 bits instead of 32.
- The output routine supports integers of any length, with the assumption that the integer is little-endian.
- The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.
- There is no need for a "filter" (mask) variable.
- The main loop does not need an
if
.
I'm happy to explain any aspect of this approach for the purposes of education.
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
add a comment |
I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.
Here's the code; it's quite simple:
#include <stdint.h>
#include <stdio.h>
static void printBinary(const uint8_t *restrict num, int bytes) {
for (int p = bytes - 1; p >= 0; p--) {
uint8_t x = num[p];
for (int i = 0; i < 8; i++) {
putchar('0' | (x >> 7));
x <<= 1;
}
}
}
int main() {
int64_t x;
for (;;) {
puts("Enter an integer: ");
if (scanf("%lld", &x) == 1)
break;
while (getchar() != 'n');
}
printBinary((uint8_t*)&x, sizeof(x));
putchar('n');
return 0;
}
Things to observe as compared to the OP's code (and RJM's code):
- There are no calls to
malloc
ormemcpy
. - The result is not stored in memory; it's output directly to
stdout
. - The input integer has a primitive form of validation. The program will loop until
scanf
succeeds. - The input integer supports 64 bits instead of 32.
- The output routine supports integers of any length, with the assumption that the integer is little-endian.
- The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.
- There is no need for a "filter" (mask) variable.
- The main loop does not need an
if
.
I'm happy to explain any aspect of this approach for the purposes of education.
I'm adding another answer in a different direction from my previous one, both to show the OP some alternative techniques, and to illustrate an adaptation of @RJM's method.
Here's the code; it's quite simple:
#include <stdint.h>
#include <stdio.h>
static void printBinary(const uint8_t *restrict num, int bytes) {
for (int p = bytes - 1; p >= 0; p--) {
uint8_t x = num[p];
for (int i = 0; i < 8; i++) {
putchar('0' | (x >> 7));
x <<= 1;
}
}
}
int main() {
int64_t x;
for (;;) {
puts("Enter an integer: ");
if (scanf("%lld", &x) == 1)
break;
while (getchar() != 'n');
}
printBinary((uint8_t*)&x, sizeof(x));
putchar('n');
return 0;
}
Things to observe as compared to the OP's code (and RJM's code):
- There are no calls to
malloc
ormemcpy
. - The result is not stored in memory; it's output directly to
stdout
. - The input integer has a primitive form of validation. The program will loop until
scanf
succeeds. - The input integer supports 64 bits instead of 32.
- The output routine supports integers of any length, with the assumption that the integer is little-endian.
- The bit sequence reversal is done directly in the decoding loop, rather than as a separate step.
- There is no need for a "filter" (mask) variable.
- The main loop does not need an
if
.
I'm happy to explain any aspect of this approach for the purposes of education.
edited 12 hours ago
answered 13 hours ago
Reinderien
3,842821
3,842821
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
add a comment |
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
Cool. Would that '0' | (x >> 7) be encoded as a '1'?
– RJM
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
@RJM Yep! Assuming that the MSB is 1.
– Reinderien
12 hours ago
1
1
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
Thanks. Good discussion. Nice to meet you.
– RJM
12 hours ago
add a comment |
// Sergio's
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary(unsigned number)
{
if (number > 1)
binary(number/2);
printf("%d", number % 2);
}
int main(void)
{
int value=10;
binary(value);
return 0;
}
New contributor
We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
add a comment |
// Sergio's
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary(unsigned number)
{
if (number > 1)
binary(number/2);
printf("%d", number % 2);
}
int main(void)
{
int value=10;
binary(value);
return 0;
}
New contributor
We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
add a comment |
// Sergio's
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary(unsigned number)
{
if (number > 1)
binary(number/2);
printf("%d", number % 2);
}
int main(void)
{
int value=10;
binary(value);
return 0;
}
New contributor
// Sergio's
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary(unsigned number)
{
if (number > 1)
binary(number/2);
printf("%d", number % 2);
}
int main(void)
{
int value=10;
binary(value);
return 0;
}
New contributor
edited yesterday
New contributor
answered yesterday
Gra8
11
11
New contributor
New contributor
We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.
We are looking for answers that provide insightful observations about the code in the question. Answers that consist of independent solutions with no justification do not constitute a code review, and may be removed.
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
add a comment |
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
5
5
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read Why are alternative solutions not welcome?
– Sᴀᴍ Onᴇᴌᴀ
yesterday
Try binary(0x80000000);
– RJM
19 hours ago
Try binary(0x80000000);
– RJM
19 hours ago
add a comment |
Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
Vengeancos is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210909%2fconvert-decimal-to-binary%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown