C语言 C - 将整数转换为二进制数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31577866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C - Convert Integer to Binary Array
提问by Fei Hap Lee
I am very new to the C language.
I will need a small program to convert intto binary and the binary preferably stored in an array so that I can further break them apart for decoding purpose.
I have following:
我对 C 语言很陌生。我需要一个小程序来转换int为二进制,二进制最好存储在一个数组中,以便我可以进一步将它们分开以进行解码。我有以下几点:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[20];
int dec = 40;
int i = 0, ArrLen;
if(dec > 0)
{
while(dec > 0)
{
arr[i] = dec % 2;
i++;
dec = dec / 2;
}
}
else
{
printf("Invalid Number");
}
}
From the code above, I can store the binaryvalue in arr.
But instead of getting the binary equivalent: 101000, the array now is like {0, 0, 0, 1, 0, 1}, which is the reversedof the correct answer.
So the question is, how to get an array in the correct order or possibly flip it?
I have one thing for sure, and that is the maximum array length will not exceed 8elements.
从上面的代码中,我可以将二进制值存储在arr. 但不是得到二进制等价物:101000,数组现在就像{0, 0, 0, 1, 0, 1},这是正确答案的相反。所以问题是,如何以正确的顺序获取数组或可能翻转它?我肯定有一件事,那就是最大数组长度不会超过8元素。
This conversion will be used repeatedly. So I plan to put it in a function so I'd be able to call the function, pass in an integer, and then get the array as the return value. So another question is, is it feasible to get an array as the return value?
此转换将重复使用。所以我打算把它放在一个函数中,这样我就可以调用该函数,传入一个整数,然后将数组作为返回值。那么另一个问题是,获取数组作为返回值是否可行?
回答by Johnny Cage
You can parameterize the array by using a pointer to int. It may be useful to parameterize the number of digits as well.
您可以使用指向 int 的指针来参数化数组。参数化位数也可能很有用。
void int_to_bin_digit(unsigned int in, int count, int* out)
{
/* assert: count <= sizeof(int)*CHAR_BIT */
unsigned int mask = 1U << (count-1);
int i;
for (i = 0; i < count; i++) {
out[i] = (in & mask) ? 1 : 0;
in <<= 1;
}
}
int main(int argc, char* argv[])
{
int digit[8];
int_to_bin_digit(40, 8, digit);
return 0;
}
回答by Martin James
or recursive V2.0:
或递归 V2.0:
#include <stdio.h>
char *binaryToAbits(unsigned int answer, char *result) {
if(answer==0) return result;
else {
result=binaryToAbits(answer>>1,result);
*result='0'+(answer & 0x01);
return result+1;
}
}
int main(void) {
unsigned int numToConvert=0x1234ABCD;
char ascResult[64];
*binaryToAbits(numToConvert,ascResult)='char *binaryToAbits(unsigned int answer, char *result) {
if(answer>1) {
result=binaryToAbits(answer>>1,result);
}
*result='0'+(answer & 0x01);
return result+1;
};
';
printf("%s",ascResult);
return 0;
}
Note, thanks to @chux, here is a better recursive function that handles the case of converting 0 - it outputs "0" instead of "":
注意,感谢@chux,这里有一个更好的递归函数来处理转换 0 的情况——它输出“0”而不是“”:
#include <math.h>
int bit_len(unsigned int n){
return floor(log(n)/log(2))+1;
}
void int_to_bin_digit(unsigned int in, int len_digitis,int* out_digit){
unsigned int mask = 1U << (len_digitis-1);
int i;
for (i = 0; i < len_digitis; i++) {
out_digit[i] = (in & mask) ? 1 : 0;
in <<= 1;
}
}
int main(int argc, char* argv[]){
int number = 30;
int len = bit_len(number);
int digits[len];
int_to_bin_digit(number,len, digits);
for( int i =0;i<len;i++){
printf("%d",digits[i]);
}
return 0;
}
回答by Marcelo de Mattos Nascimento
Same answer as Johnny Cage with the addtion of a function to get the length of a digit
与 Johnny Cage 相同的答案,但添加了一个函数来获取数字的长度
#include <stdio.h>
void intToBin(int dec, int bin[], int numBits){
for(int i = 0; i < numBits; i++){
bin[i] = 1 & (dec >> i);
}
}
void printArr(int arr[], int arrSize){
for(int i = 0; i < arrSize; i++) {
printf("%d ", arr[i]);
}
}
int main(int argc, char* argv[]){
int bin[32];
intToBin(-15, bin, 32);
printArr(bin, 32);
}
回答by Takao Shibamoto
This should work.
这应该有效。
uint8_t * intToBin(int x) {
uint8_t *bin = (int *) malloc(8);
uint8_t i = 0;
int mask = 0x80;
for (i = 0; i < 8; i++) {
bin[i] = (x & mask) >> (7-i);
mask >>= 1;
}
return bin;
}
回答by M. Shaw
Try something like this:
尝试这样的事情:
for(int i = 0 ; i < 8 ; i++)
{
bytearray[i] = inputint & pow(2,7-i);
}
Include <stdint.h>for the declaration of uint8_t.
Remember to freethe malloc-ed memory if you don't want memory leaks.
包括<stdint.h>用于声明uint8_t. 请记住,free在malloc-ed内存,如果你不想内存泄漏。
回答by ydobonebi
Using bitwise logic :
使用按位逻辑:
void binary(unsigned n)
{
unsigned i;
for (i = 1 << 31; i > 0; i = i / 2)
(n & i)?`/*STORE 1*/` : `/*STORE 0*/` ;
}
回答by TryinHard
This may be helpful:
这可能会有所帮助:
int arr[200]; //for storing the binary representation of num
int i=0; // to keep the count of the no of digits in the binary representation
void calBinary(int n) // function to recalculate
{
if(n>1)
calBinary(n/2);
arr[i++]=n%2;
}
回答by Kaustav Ray
Recursive Implementation:
递归实现:
(Since you cannot have the prior idea of number of digits(0/1) in the binary format of the given number)
(因为您无法预先了解给定数字的二进制格式中的位数(0/1))
##代码##
