PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

[FIXED] How to write integers with write() function in C?

 July 19, 2022     c, command, integer     No comments   

Issue

I'm a noob on C and trying to use write() function to show an integer.

These is my code:

int n = 7;
write(1, &n, 4);

I want to show 7, but the program shows nothing or other strange character when I set n to a big number.

What am I missing?


Solution

Objects like int are represented in memory with various bits. The write routine transmits exactly those bits of memory to its destination.

Terminals are not designed to display arbitrary bits of memory. They do not interpret the bits to mean an int or other object and then display that interpretation. Generally, we transmit characters to terminals. More specifically, we send codes that represent characters. Terminals are designed to receive these codes and display little pictures of writing (characters, glyphs, emoji, whatever).

To make a terminal display “7”, we need to send it the code for “7”. A common code system for characters is ASCII (American Standard Code for Information Interchange). The ASCII code for “7” is 55. So, if you do this:

char x = 55;
write(1, &x, 1);

then the terminal will draw “7” on its display, if ASCII is being used.

So write is the wrong routine to use to display int values for a human to read. Instead, you normally use printf, like this:

printf("%d", n);

The f in printf stands for formatted. It examines the bits that represent the value in n and formats the represented value as characters intended for humans to read, and then it writes those characters to standard output.

If you want to use write to transmit characters to the terminal, you can use sprintf to get just the formatting part of printf without the printing part. For starters, this code will work:

char buffer[80];                            // Make space for sprintf to work in.
int LengthUsed = sprintf(buffer, "%d", n);  // Format n in decimal.
write(1, buffer, LengthUsed);               // Write the characters.

(More sophisticated code would adapt the buffer size to what is needed for the sprintf.)



Answered By - Eric Postpischil
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing