Article View: be.comp.programming
Article #3667Re: binary string als int afdrukken in C
From: Gunter Schelfhout
Date: Sat, 29 Nov 2003 23:43
Date: Sat, 29 Nov 2003 23:43
45 lines
2254 bytes
2254 bytes
staf wagemakers wrote:
> On 2003-11-29, Gunter Schelfhout <nospam@please.com> wrote:
>> Hoe kan een string (bv "1100100101001001") afdrukken als een int in C met
>> behulp van de functies in glibc?
>> Met printf?
>
> er bestaat hievoor geen standaard functie voor in libc
> ...of ik ken hem niet ;-)
>
> het is echter niet zo moeilijk om van een "binstring" een integer te
> maken, enkel karakter is bit*2^plaats waard.
>
> char str[] = "1111111111111111";
> int i=0;
> int shift=0;
> char *c;
>
> for (c=str+strlen(str)-1;*c!='\0';c--) {
>
> int bit=0;
> if(*c!='0') bit = 1;
> i+=(bit<<shift++);
> }
> printf("i = %d\n",i);
>
Ik had het ondertussen in die aard opgelost: (eenvoudig, zonder checking en
voor range 0-255)
char* dec_bin(int dec) {
char* c;
char* bin;
bin = (char *) malloc(9 * sizeof(char));
int k;
for (k = 7; k >= 0; k--) {
c = "0";
if ((1 << k) & dec)
c = "1";
strcat(bin, c);
}
return bin;
}
--
Blood, sweat & tears
Technical Details
Message-ID:
<naayb.51725$Ee3.1727588@phobos.telenet-ops.be>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news2.google.com!news.maxwell.syr.edu!skynet.be!skynet.be!ossa.telenet-ops.be!phobos.telenet-ops.be.POSTED!not-for-mailReferences:
<td1yb.50435$xX1.1629315@phobos.telenet-ops.be> <slrnbshhuh.3sc.staf_nospam_@localhost.staflaptop>Show Full Headers
Complete Article Headers
X-Google-Language: DUTCH,ASCII-7-bit X-Google-Thread: fcea4,12763d3d6faef1bf X-Google-Attributes: gidfcea4,public X-Google-ArrivalTime: 2003-11-29 15:43:15 PST Path: arc1-ca.pugleaf.net!archiver1.google.com!news2.google.com!news.maxwell.syr.edu!skynet.be!skynet.be!ossa.telenet-ops.be!phobos.telenet-ops.be.POSTED!not-for-mail From: Gunter Schelfhout <nospam@please.com> Subject: Re: binary string als int afdrukken in C Newsgroups: be.comp.programming References: <td1yb.50435$xX1.1629315@phobos.telenet-ops.be> <slrnbshhuh.3sc.staf_nospam_@localhost.staflaptop> Lines: 45 User-Agent: KNode/0.7.2 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7Bit Message-ID: <naayb.51725$Ee3.1727588@phobos.telenet-ops.be> Date: Sat, 29 Nov 2003 23:43:15 GMT NNTP-Posting-Host: 213.118.155.190 X-Complaints-To: abuse@telenet.be X-Trace: phobos.telenet-ops.be 1070149395 213.118.155.190 (Sun, 30 Nov 2003 00:43:15 MET) NNTP-Posting-Date: Sun, 30 Nov 2003 00:43:15 MET Organization: Telenet Internet