473,652 Members | 3,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using binary numbers in c

Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
similarly, in printf, we have %d for an decimal number %x and %o for hex and
octal numbers... how about binary numbers??

Thank you very much...
--
{ Kelvin@!!! }
Nov 14 '05 #1
6 10540
On Thu, 06 May 2004 01:18:56 GMT, "Kelvin@!!! " <ke*******@shaw .ca.ca>
wrote:
Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
similarly, in printf, we have %d for an decimal number %x and %o for hex and
octal numbers... how about binary numbers??

Thank you very much...


Here's something I picked up from, I believe, this very newsgroup not long
back:

------------- macros.h: ---------------------------------

/*
macros.h:
Binary constant generator macro
By Tom Torfs - donated to the public domain
*/

/* All macro's evaluate to compile-time constants */

/* *** helper macros *** */

/* turn a numeric literal into a hex constant
(avoids problems with leading zeroes)
8-bit constants max value 0x11111111, always fits in unsigned long
*/
#define HEX__(n) 0x##n##LU

/* 8-bit conversion function */
#define B8__(x) ((x&0x0000000FL U)?1:0) \
+((x&0x000000F0 LU)?2:0) \
+((x&0x00000F00 LU)?4:0) \
+((x&0x0000F000 LU)?8:0) \
+((x&0x000F0000 LU)?16:0) \
+((x&0x00F00000 LU)?32:0) \
+((x&0x0F000000 LU)?64:0) \
+((x&0xF0000000 LU)?128:0)

/* *** user macros *** */

/* for upto 8-bit binary constants */
#define B8(d) ((unsigned char)B8__(HEX__ (d)))

/* for upto 16-bit binary constants, MSB first */
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)< <8) \
+ B8(dlsb))

/* for upto 32-bit binary constants, MSB first */
#define B32(dmsb,db2,db 3,dlsb) (((unsigned long)B8(dmsb)<< 24) \
+ ((unsigned long)B8(db2)<<1 6) \
+ ((unsigned long)B8(db3)<<8 ) \
+ B8(dlsb))

/* Sample usage:
B8(01010101) = 85
B16(10101010,01 010101) = 43605
B32(10000000,11 111111,10101010 ,01010101) = 2164238933
*/

------------ test.c ---------------------

#include <stdio.h>
#include "macros.h"

int main()
{
int i = B8(1010);
int j = B8(10000000);

printf("i = %d, j = %d\n", i, j);
return 0;
}
HTH,
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2

"Kelvin@!!! " <ke*******@shaw .ca.ca> wrote in message
news:4ogmc.3842 22$Ig.25579@pd7 tw2no...
Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
First let me dispel what I think is an erroneous notion you have.
All numbers are stored as 'binary'. When you talk about e.g.
'decimal', 'binary', 'hex', etc., you're talking about the
*textual* representation of a number, e.g. using digits 0-9,
0 and 1, 0 - F, etc.

That said, no, C has no syntax for expressing a binary pattern in source
code. Hex is as close (and imo more 'convenient') as it gets.
similarly, in printf, we have %d for an decimal number %x and %o for hex and octal numbers... how about binary numbers??


Nope, printf() doesn't have a type specifier for "zero and one"
representation. But it's trivial to write a function
to produce a string of zero and one characters from an integer,
then use %s with its output.

Hints:

x % 2;
x /= 2;

A function could also be written to input a string containing
zeros and ones and convert it to a numeric type.

-Mike
Nov 14 '05 #3

"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:d4******** *************** *********@4ax.c om...
On Thu, 06 May 2004 01:18:56 GMT, "Kelvin@!!! " <ke*******@shaw .ca.ca>
wrote:
Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
similarly, in printf, we have %d for an decimal number %x and %o for hex andoctal numbers... how about binary numbers??

Thank you very much...
Here's something I picked up from, I believe, this very newsgroup not long
back:

------------- macros.h: ---------------------------------

/*
macros.h:
Binary constant generator macro
By Tom Torfs - donated to the public domain
*/

/* All macro's evaluate to compile-time constants */

/* *** helper macros *** */

/* turn a numeric literal into a hex constant
(avoids problems with leading zeroes)
8-bit constants max value 0x11111111, always fits in unsigned long
*/
#define HEX__(n) 0x##n##LU

/* 8-bit conversion function */
#define B8__(x) ((x&0x0000000FL U)?1:0) \
+((x&0x000000F0 LU)?2:0) \
+((x&0x00000F00 LU)?4:0) \
+((x&0x0000F000 LU)?8:0) \
+((x&0x000F0000 LU)?16:0) \
+((x&0x00F00000 LU)?32:0) \
+((x&0x0F000000 LU)?64:0) \
+((x&0xF0000000 LU)?128:0)

/* *** user macros *** */

/* for upto 8-bit binary constants */
#define B8(d) ((unsigned char)B8__(HEX__ (d)))

/* for upto 16-bit binary constants, MSB first */
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)< <8) \
+ B8(dlsb))

/* for upto 32-bit binary constants, MSB first */
#define B32(dmsb,db2,db 3,dlsb) (((unsigned long)B8(dmsb)<< 24) \
+ ((unsigned long)B8(db2)<<1 6) \
+ ((unsigned long)B8(db3)<<8 ) \
+ B8(dlsb))

/* Sample usage:
B8(01010101) = 85
B16(10101010,01 010101) = 43605
B32(10000000,11 111111,10101010 ,01010101) = 2164238933
*/

------------ test.c ---------------------

#include <stdio.h>
#include "macros.h"

int main()
{
int i = B8(1010);
int j = B8(10000000);

printf("i = %d, j = %d\n", i, j);
return 0;
}
HTH,
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html


thank you for the code...
but ... #define HEX__(n) 0x##n##LU


what does the # stands for here???

--
{ Kelvin@!!! }
Nov 14 '05 #4
Kelvin@!!! <ke*******@shaw .ca.ca> scribbled the following:
"Leor Zolman" <le**@bdsoft.co m> wrote in message
news:d4******** *************** *********@4ax.c om...
Here's something I picked up from, I believe, this very newsgroup not long
back:

(snip)
thank you for the code...
but ...
#define HEX__(n) 0x##n##LU
what does the # stands for here???


Assuming you know what #define means and are asking about the ##:
It's a preprocessor operator that "glues" two preprocessing tokens into
one C token. Here it's used twice, gluing three preprocessing tokens
together. The first is 0x, the second is whatever n gets replaced with,
and the third is LU. For example HEX__(0) would be expanded to a glued
together token 0x0LU. The C compiler itself treats this as a single
token and not as three tokens after each other.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"It sure is cool having money and chicks."
- Beavis and Butt-head
Nov 14 '05 #5
"Kelvin@!!! " <ke*******@shaw .ca.ca> wrote in message
news:4ogmc.3842 22$Ig.25579@pd7 tw2no...
Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
similarly, in printf, we have %d for an decimal number %x and %o for hex and octal numbers... how about binary numbers??


There isn't a way to do that, as the compiler does know from binary.

OTOH, you could write a pre-processor that does that, if you wish. It would
take your new symbol, say 0b11110000 and turn it into 0xF0, then pass it
into the compiler.

For printf(), you'd have to write a function to change hex to a binary
string, I surmise. It would have to be at run-time since the variables, are.

--
Mabden
Nov 14 '05 #6
http://www.eskimo.com/~scs/C-faq/q20.11.html

--
~Kieran Simkin
Digital Crocus
http://digital-crocus.com/

"Kelvin@!!! " <ke*******@shaw .ca.ca> wrote in message
news:4ogmc.3842 22$Ig.25579@pd7 tw2no...
Hi everyone:
when we wanna use hex numbers in C, we usually write something like:
int hex_num = 0x12F9;

but how can I declare a binary number in a similar way by putting some
leading words to tell the complier this is a binary number???
similarly, in printf, we have %d for an decimal number %x and %o for hex and octal numbers... how about binary numbers??

Thank you very much...
--
{ Kelvin@!!! }

Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
15052
by: Elliot Marks | last post by:
I want to output this data to text and binary files. The binary file contains the garbage you would expect to see if you try to read it with a text editor, but below that the output appears as text as it also appears in the text file. It's been a long time since I've written any VB code. What am I doing wrong? (The default value of modulus is 255.) Private Sub cmdStart_Click() 'samples an image at intervals depending on the settings
52
5868
by: Dick Moores | last post by:
I need to figure out how to compute pi to base 12, to as many digits as possible. I found this reference, <http://mathworld.wolfram.com/Base.html>, but I really don't understand it well enough. Could someone show me how to do what I need? Thanks, Dick Moores rdm@rcblue.com
20
7540
by: Christian Stigen Larsen | last post by:
A signed int reserves one bit to signify whether a number is positive or negative. In light of this, a colleague asked me whether there existed an int in C++ that was -0, a zero with the negative bit set. I was intrigued by this, so I tried the following code: #include <stdio.h> int main(int, char**) { int a(-0); printf("a=%d\n", a);
18
22595
by: Bern | last post by:
how to specifiy a binary number in c++? hex numbers are specified by 0x prefix
3
9613
by: Tanuki | last post by:
Hi All: I encounter a programming problem recently. I need to read a binary file. I need to translate the binary data into useful information. I have the format at hand, like 1st byte = ID, next 4 byte (int) = serial number etc. The first problem is Big Endian/ Little Endian problem. I can decipher if the format is big or little endian. But got confuse as to how to decipher the data.
21
3818
by: nicolasg | last post by:
does anyone know a module or something to convert numbers like integer to binary format ? for example I want to convert number 7 to 0111 so I can make some bitwise operations... Thanks
29
5086
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is: 65,535. But i'm trying to write a program to test this, assuming I didn't know this number in advance. I came up with the following but have two questions. Maybe someone can help? using System; using System.Collections.Generic; using System.Text;
11
3581
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function Read_bin(ByVal ruta As String) Dim cadena As String = "" Dim dato As Array If File.Exists(ruta) = True Then
0
28053
Frinavale
by: Frinavale | last post by:
Convert a Hex number into a decimal number and a decimal number to Hex number This is a very simple script that converts decimal numbers into hex values and hex values into decimal numbers. The example following this one demonstrates how to convert decimal numbers into binary values. A hex number is a string that contains numbers between 0-9 and characters A-F; where A = 10, B = 11, ..., F = 15. (For more information please look up...
0
8367
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8811
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8703
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8589
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5619
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4145
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2703
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1591
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.