By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,203 Members | 1,358 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,203 IT Pros & Developers. It's quick & easy.

Write a program to print out the binary value of a 16 bit number.

P: 2
#include <stdio.h>
#include <stdlib.h>

int main()
int i, count, mask;

i = 0xF5A2;
mask = 0x8000;
printf("Hex value= %x, Binary=", i, mask);

if(i & mask)

mask = mask >> 1;


return 0;
Feb 1 '17 #1
Share this Question
Share on Google+
3 Replies

P: 2
what am i missing? every time i use the program i get a binary of 111111111111111
Feb 1 '17 #2

Expert Mod 5K+
P: 9,197
Your mask is not shifting right unless you print a 0. Since you don't print 0, the mask never shifts.
Feb 2 '17 #3

Expert 100+
P: 2,400
Look at the first printf (the one that prints the hex value). You pass two arguments after the format string (i and mask), but the format string has only one conversion specifier. You might as well not pass mask.

The int type is allowed to be as small as 16 bits. If it is indeed 16 bits for your compiler, then odd things could happen when the most significant bit is set. You might want to declare i and mask as long or unsigned int to avoid inadvertently creating negative values. You will have to update the format string used to print i accordingly.

You should get in the habit of printing a newline at the end of every line to insure the output buffer is flushed. Refer to this earlier post for an explanation of buffered versus nonbuffered I/O.
Feb 2 '17 #4

Post your reply

Sign in to post your reply or Sign up for a free account.