Host introspection: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Python}}: Add word size)
(→‎{{header|Python}}: Added hostname)
Line 39: Line 39:
>>> sys.byteorder
>>> sys.byteorder
little
little
>>> import socket
>>> socket.gethostname()
'PADDY3118-RESTING'
>>> </python>
>>> </python>

Revision as of 05:42, 11 October 2008

Task
Host introspection
You are encouraged to solve this task according to the task description, using any language you may know.

Print the word size and endianness of the host machine.

C

<c>#include <stdio.h>

int main() {

   int one = 1;
   printf("word size = %d\n", 8 * sizeof(void *)); // a pointer takes up a word
   if (*(char *)&one) // if the least significant bit is located in the lowest-address byte
       printf("little endian\n");
   else
       printf("big endian\n");
   return 0;

}</c>

Forth

: endian
  cr 1 cells . ." address units per cell"
  s" ADDRESS-UNIT-BITS" environment? if cr . ." bits per address unit" then
  cr 1 here ! here c@ if ." little" else ." big" then ."  endian" ;

This relies on c@ being a byte fetch (4 chars = 1 cells). Although it is on most architectures, ANS Forth only guarantees that 1 chars <= 1 cells. Some Forths like OpenFirmware have explicitly sized fetches, like b@.

J

   ":&> (|: 32 64 ;"0 big`little) {"_1~ 2 2 #: 16b_e0 + a. i. 0 { 3!:1 ''  
32
little

OCaml

Print word size: <ocaml>Printf.printf "%d\n" Sys.word_size</ocaml> Dunno about endianness

Python

<python>>>> import sys, math >>> int(round(math.log(sys.maxint,2)+1)) 32 >>> sys.byteorder little >>> import socket >>> socket.gethostname() 'PADDY3118-RESTING' >>> </python>