C: get the bits of an integer Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag? The Ask Question Wizard is Live!Right shifting negative numbers in CHow do you set, clear, and toggle a single bit?How to count the number of set bits in a 32-bit integer?How do I generate random integers within a specific range in Java?Convert a string to an integer in JavaScript?Improve INSERT-per-second performance of SQLite?Generate random integers between 0 and 9stdlib.h not working as intended with atoi() functionmain() function with wrong signature gets calledComand line argument to variable as integerVigénere Cipher in C

String `!23` is replaced with `docker` in command line

What causes the vertical darker bands in my photo?

Why are there no cargo aircraft with "flying wing" design?

How to tell that you are a giant?

ListPlot join points by nearest neighbor rather than order

What's the purpose of writing one's academic biography in the third person?

Identifying polygons that intersect with another layer using QGIS?

Storing hydrofluoric acid before the invention of plastics

Do I really need recursive chmod to restrict access to a folder?

Why did the rest of the Eastern Bloc not invade Yugoslavia?

Is there a (better) way to access $wpdb results?

Why am I getting the error "non-boolean type specified in a context where a condition is expected" for this request?

Identify plant with long narrow paired leaves and reddish stems

Apollo command module space walk?

Why is "Consequences inflicted." not a sentence?

Can a USB port passively 'listen only'?

What's the meaning of 間時肆拾貳 at a car parking sign

Can an alien society believe that their star system is the universe?

What exactly is a "Meth" in Altered Carbon?

Output the ŋarâþ crîþ alphabet song without using (m)any letters

How to call a function with default parameter through a pointer to function that is the return of another function?

Extract all GPU name, model and GPU ram

How can I make names more distinctive without making them longer?

How does the particle を relate to the verb 行く in the structure「A を + B に行く」?



C: get the bits of an integer



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?
The Ask Question Wizard is Live!Right shifting negative numbers in CHow do you set, clear, and toggle a single bit?How to count the number of set bits in a 32-bit integer?How do I generate random integers within a specific range in Java?Convert a string to an integer in JavaScript?Improve INSERT-per-second performance of SQLite?Generate random integers between 0 and 9stdlib.h not working as intended with atoi() functionmain() function with wrong signature gets calledComand line argument to variable as integerVigénere Cipher in C



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-3















I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
int vals1[32], vals2[32];
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);

// so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form



Any suggestions?










share|improve this question



















  • 1





    Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

    – Bathsheba
    Mar 8 at 16:02












  • Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

    – Superlokkus
    Mar 8 at 16:02











  • What have you tried so far? Where specifically are you stuck?

    – Govind Parmar
    Mar 8 at 16:03











  • @Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

    – Ben deVries
    Mar 8 at 16:59











  • int nthbit(unsigned long long x, int n) return (x >> n) & 1;

    – pmg
    Mar 8 at 17:24

















-3















I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
int vals1[32], vals2[32];
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);

// so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form



Any suggestions?










share|improve this question



















  • 1





    Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

    – Bathsheba
    Mar 8 at 16:02












  • Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

    – Superlokkus
    Mar 8 at 16:02











  • What have you tried so far? Where specifically are you stuck?

    – Govind Parmar
    Mar 8 at 16:03











  • @Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

    – Ben deVries
    Mar 8 at 16:59











  • int nthbit(unsigned long long x, int n) return (x >> n) & 1;

    – pmg
    Mar 8 at 17:24













-3












-3








-3








I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
int vals1[32], vals2[32];
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);

// so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form



Any suggestions?










share|improve this question
















I have a program that will take two 4-byte integers as input and I need to store these into integer arrays like so...



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
int vals1[32], vals2[32];
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);

// so argv[1] might be 47 and I would want to set the values of the vals1 array to reflect that in binary form



Any suggestions?







c binary integer






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 17:14









chqrlie

63.9k851108




63.9k851108










asked Mar 8 at 16:00









Ben deVriesBen deVries

52




52







  • 1





    Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

    – Bathsheba
    Mar 8 at 16:02












  • Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

    – Superlokkus
    Mar 8 at 16:02











  • What have you tried so far? Where specifically are you stuck?

    – Govind Parmar
    Mar 8 at 16:03











  • @Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

    – Ben deVries
    Mar 8 at 16:59











  • int nthbit(unsigned long long x, int n) return (x >> n) & 1;

    – pmg
    Mar 8 at 17:24












  • 1





    Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

    – Bathsheba
    Mar 8 at 16:02












  • Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

    – Superlokkus
    Mar 8 at 16:02











  • What have you tried so far? Where specifically are you stuck?

    – Govind Parmar
    Mar 8 at 16:03











  • @Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

    – Ben deVries
    Mar 8 at 16:59











  • int nthbit(unsigned long long x, int n) return (x >> n) & 1;

    – pmg
    Mar 8 at 17:24







1




1





Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

– Bathsheba
Mar 8 at 16:02






Hints: for a positive number, '% 2' extracts the least significant binary digit, and / 2 removes the final binary digit.

– Bathsheba
Mar 8 at 16:02














Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

– Superlokkus
Mar 8 at 16:02





Your question is unclear. So is your input a string? Do you want to just store that as an int into an int array? Do you want a binary representation of your int? What representation?

– Superlokkus
Mar 8 at 16:02













What have you tried so far? Where specifically are you stuck?

– Govind Parmar
Mar 8 at 16:03





What have you tried so far? Where specifically are you stuck?

– Govind Parmar
Mar 8 at 16:03













@Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

– Ben deVries
Mar 8 at 16:59





@Superlokkus, i am taking a cstring which i will cast to an integer using the atoi function. So, i start with "47" and turn it into the integer 47, but then want to extract the binary bits that represent 47 as an integer and store them in val1

– Ben deVries
Mar 8 at 16:59













int nthbit(unsigned long long x, int n) return (x >> n) & 1;

– pmg
Mar 8 at 17:24





int nthbit(unsigned long long x, int n) return (x >> n) & 1;

– pmg
Mar 8 at 17:24












1 Answer
1






active

oldest

votes


















1














First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer



int n = 47;
for (int i = 0; i < 32; i++)

/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %drn", i, (unsigned int)((n >> i) & 1));



So, using shift operator, solution to your problem would be something like



void fun(int n1, int n2)

int i, argv1[32], argv2[32];

for (i = 0; i < 32; i++)

argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;




You have to be careful about the bit order i.e. which bit are being stored at which of the array index.






share|improve this answer




















  • 1





    n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

    – chqrlie
    Mar 8 at 17:17











  • Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

    – Mazhar
    Mar 8 at 17:20






  • 1





    @Mazhar This explains it.

    – Michail
    Mar 8 at 17:35






  • 1





    Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

    – chqrlie
    Mar 8 at 17:38






  • 1





    I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

    – chqrlie
    Mar 8 at 18:00











Your Answer






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: "1"
;
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: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
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
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066814%2fc-get-the-bits-of-an-integer%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer



int n = 47;
for (int i = 0; i < 32; i++)

/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %drn", i, (unsigned int)((n >> i) & 1));



So, using shift operator, solution to your problem would be something like



void fun(int n1, int n2)

int i, argv1[32], argv2[32];

for (i = 0; i < 32; i++)

argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;




You have to be careful about the bit order i.e. which bit are being stored at which of the array index.






share|improve this answer




















  • 1





    n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

    – chqrlie
    Mar 8 at 17:17











  • Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

    – Mazhar
    Mar 8 at 17:20






  • 1





    @Mazhar This explains it.

    – Michail
    Mar 8 at 17:35






  • 1





    Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

    – chqrlie
    Mar 8 at 17:38






  • 1





    I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

    – chqrlie
    Mar 8 at 18:00















1














First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer



int n = 47;
for (int i = 0; i < 32; i++)

/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %drn", i, (unsigned int)((n >> i) & 1));



So, using shift operator, solution to your problem would be something like



void fun(int n1, int n2)

int i, argv1[32], argv2[32];

for (i = 0; i < 32; i++)

argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;




You have to be careful about the bit order i.e. which bit are being stored at which of the array index.






share|improve this answer




















  • 1





    n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

    – chqrlie
    Mar 8 at 17:17











  • Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

    – Mazhar
    Mar 8 at 17:20






  • 1





    @Mazhar This explains it.

    – Michail
    Mar 8 at 17:35






  • 1





    Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

    – chqrlie
    Mar 8 at 17:38






  • 1





    I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

    – chqrlie
    Mar 8 at 18:00













1












1








1







First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer



int n = 47;
for (int i = 0; i < 32; i++)

/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %drn", i, (unsigned int)((n >> i) & 1));



So, using shift operator, solution to your problem would be something like



void fun(int n1, int n2)

int i, argv1[32], argv2[32];

for (i = 0; i < 32; i++)

argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;




You have to be careful about the bit order i.e. which bit are being stored at which of the array index.






share|improve this answer















First task would be to convert a char * to an int, which you said you can. So here comes the next part i.e. getting the binary representation. For getting the binary representation of any data type, usage of Shift Operator is one of the best ways. And you can get it by performing shift on the data type and then performing Bitwise AND i.e. & with 1. For example, if n is an integer



int n = 47;
for (int i = 0; i < 32; i++)

/* It's going to print the values of bits starting from least significant. */
printf("Bit%d = %drn", i, (unsigned int)((n >> i) & 1));



So, using shift operator, solution to your problem would be something like



void fun(int n1, int n2)

int i, argv1[32], argv2[32];

for (i = 0; i < 32; i++)

argv1[i] = ((unsigned int)n1 >> i) & 1;
argv2[i] = ((unsigned int)n2 >> i) & 1;




You have to be careful about the bit order i.e. which bit are being stored at which of the array index.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 18:00









chqrlie

63.9k851108




63.9k851108










answered Mar 8 at 17:01









MazharMazhar

564520




564520







  • 1





    n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

    – chqrlie
    Mar 8 at 17:17











  • Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

    – Mazhar
    Mar 8 at 17:20






  • 1





    @Mazhar This explains it.

    – Michail
    Mar 8 at 17:35






  • 1





    Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

    – chqrlie
    Mar 8 at 17:38






  • 1





    I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

    – chqrlie
    Mar 8 at 18:00












  • 1





    n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

    – chqrlie
    Mar 8 at 17:17











  • Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

    – Mazhar
    Mar 8 at 17:20






  • 1





    @Mazhar This explains it.

    – Michail
    Mar 8 at 17:35






  • 1





    Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

    – chqrlie
    Mar 8 at 17:38






  • 1





    I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

    – chqrlie
    Mar 8 at 18:00







1




1





n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

– chqrlie
Mar 8 at 17:17





n1 >> i has implementation defined behavior if n1 is negative. You should use (unsigned int)n1 >> i

– chqrlie
Mar 8 at 17:17













Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

– Mazhar
Mar 8 at 17:20





Like what exactly what happen if n1 is negative for example, please elaborate a bit more. Thanks a lot.

– Mazhar
Mar 8 at 17:20




1




1





@Mazhar This explains it.

– Michail
Mar 8 at 17:35





@Mazhar This explains it.

– Michail
Mar 8 at 17:35




1




1





Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

– chqrlie
Mar 8 at 17:38





Another point: you make the silent assumption that sizeof(int) == 4 because you use for (i = 0; i < (8 * sizeof(int)); i++) and the sizes have a fixed size of 32. Better write for (i = 0; i < 32; i++)

– chqrlie
Mar 8 at 17:38




1




1





I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

– chqrlie
Mar 8 at 18:00





I took the liberty to fix the parentheses in the answer's code: n1 must be cast before the >> operation.

– chqrlie
Mar 8 at 18:00



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • 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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066814%2fc-get-the-bits-of-an-integer%23new-answer', 'question_page');

);

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







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович