Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Write a program or function that outputs an L if run on a little endian architecture or a B if run on a big endian architecture. Lower case output l or b is also acceptable.

There is no input.

Scoring is code golf.

Edit: As per the comments below, I am clarifying that the entry must be able to run on either architecture.

I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.

share|improve this question
    
Does the little endian apply only to the memory, or every byte in the program source code as well? – Leaky Nun 2 days ago
5  
I think this is an interesting challenge (and it's way out of the norm) but it's going to be extremely hard to test it. Especially since most of the code will end up being extremely platform specific. – Dr Green Eggs and Iron Man 2 days ago
3  
Yeah I think it'll be interesting because hopefully it's something that esolangs and golfing languages have a harder time with than 'normal' languages. I have a feeling that they won't be that hard to verify. Worst case they should be verifiable by hand – Liam 2 days ago
2  
I guess an answer based on a specific machine code is forbidden? Otherwise B0 4C C3, which is mov al, 'L' / ret or unsigned char f(){ return 'L'; }, would be a valid x86 answer. – Margaret Bloom yesterday
1  
If someone wants to test with a big endian architecture, here are some ways: How to test your code on a machine with big-endian architecture?, Imitate/emulate a big-endian behavior in C?. Another way may be running your app in your ARM phone in big endian mode – Lưu Vĩnh Phúc 13 hours ago

30 Answers 30

C, 26 bytes

a=66<<24|76;f(){puts(&a);}

Assumes 32-bit int and ASCII characters. Tested on amd64 (little-endian) and mips (big-endian).

GCC, 23 bytes

00000000: 613d 2742 0000 4c27 3b66 2829 7b70 7574  a='B..L';f(){put
00000010: 7328 2661 293b 7d                        s(&a);}

Suggested by feersum. The value of multi-character constants is implementation-dependent, but this seems to work in GCC. Tested on the same architectures.

share|improve this answer
5  
Shorter is a='B\0\0L'; The \0s can be replaced with null bytes. – feersum yesterday
1  
@feersum The endianness of multi-character constants seems to be implementation dependent. I wouldn't normally worry about that much in code golf, but this challenge is all about distinguishing between implementations. – Anders Kaseorg yesterday
    
Does this code currently work in something other than GCC? – feersum yesterday
1  
@feersum C89 allows both. – Anders Kaseorg yesterday
1  
Using xlc (VisualAge C++ Professional / C for AIX Compiler, Version 6) on an RS6000 running AIX 5.2 the 26 byte program successfully prints "B" – Jerry Jeremiah yesterday

Python, 33 bytes

import sys
exit(sys.byteorder[0])

sys.byteorder is either 'little' or 'big' (and for those of you who will read this sentence without looking at the code, [0] means take the first character).

share|improve this answer
    
The challenge says the output must be L and B (or the lowercase variant), not the entire word. – user2428118 yesterday
24  
That's why it says sys.byteorder[0], i.e. the first char of byteorder. – the_Seppi yesterday

MATLAB / Octave, 24 bytes

[~,~,e]=computer;disp(e)

The computer function gives information about, well, the computer it's running on. The third output is endianness: L or B for little- or big-endian respectively.

Try it on Ideone.

share|improve this answer
    
what. This is somethign for stackoverflow, I didnt know this! – Ander Biguri yesterday

JavaScript ES6, 50 bytes

_=>"BL"[new Int8Array(Int16Array.of(1).buffer)[0]]

I don’t know who decided it was a good idea for TypedArray objects to expose the native endianness of the interpreter, but here we are.

share|improve this answer
1  
WebGL people thought it was a good idea, to avoid having to convert endianness when passing to the GPU. Pretty much everyone else thought it stupid… :( – gsnedders 10 hours ago

C, 36 35 bytes

1 byte thanks to @algmyr and @owacoder.

main(a){printf(*(char*)&a?"L":"B");}
main(a){putchar(66+10**(char*)&a);}
main(a){putchar("BL"[*(char*)&a]);}

Credits here.

Untested since I don't have a big-endian machine.

share|improve this answer
2  
Does the C spec allow a one-argument main function? – CodesInChaos yesterday
    
@codesinchaos yes it does. It will be the number of command line arguments given. Usually here it is used to have a variable initiated to 1 because no input is given (and the program name always counts as the first argument) – Liam yesterday
2  
@Liam: If anything other than 0 or 2 is allowed is implementation defined in C11. – Hurkyl yesterday
    
I like how this could be broken by adding enough input arguments to either have a multiple of 255 or populate the top octet. – algmyr yesterday
1  
Or main(a){putchar("BL"[*(char*)&a]);}. – owacoder yesterday

Java 8, 96, 64 52 bytes

()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0);

A golf based on this SO answer. All credit goes to @LeakyNun and @AlanTuning. Java keeps the loosing streak.

96 bytes:

 char e(){return java.nio.ByteOrder.nativeOrder().equals(java.nio.ByteOrder.BIG_ENDIAN)?'b':'l';}

64 bytes:

char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);}

Untested b/c I don't have access to a big-endian machine.

share|improve this answer
1  
char e(){return(""+java.nio.ByteOrder.nativeOrder()).charAt(0);} – Leaky Nun yesterday
    
char e(){return(""+java.nio.Bits.byteOrder()).charAt(0);} – Leaky Nun yesterday
    
@LeakyNun I don't see Bits in the Java API, and when I run it it gives me "Bits is not public in java.nio" – Blue yesterday
    
Oh, alright then. – Leaky Nun yesterday
    
52 bytes if you use a lambda! ()->(""+java.nio.ByteOrder.nativeOrder()).charAt(0); – Alan Tuning yesterday

(G)Forth, 24 bytes

here $4200004C , c@ emit

Assumes that cells are 32 bits (and that your Forth interpreter supports Gforth's base prefixes). It simply stores the number 0x4200004C in memory and then displays the byte at the low end.

share|improve this answer

Mathematica, 22

{B,L}[[$ByteOrdering]]

This probably breaks some rule about not using a built-in function but I'm not really interested in rube goldberging an alternative.

share|improve this answer
1  
Built-ins are fine (most answers are using them too) – Liam yesterday
1  
And once again, Mathematica has a built-in! – gcampbell yesterday
1  
I think this is a snippet, not a program or function, and you should add & to make it a function. (But there may be disagreement over what constitutes a “program”.) – Anders Kaseorg yesterday
1  
@Anders I am not really familiar with the current standards for PCG (if I ever was) but IMHO one advantage of an interpreted language is that a snippet is a program. This can be run in a stand-alone manner as much as any other program in Mathematica. – Mr.Wizard 18 hours ago

Perl, 38 36 bytes

say+(pack"L",1 eq pack"V",1)?"L":"B"

Works by packing a number in the system's default byte order and comparing it to a number packed in little-endian byte order.

share|improve this answer

Common Lisp, 27 bytes

Tested on SBCL and ECL. For a portable approach, one should use trivial-features.

(lambda()'L #+big-endian'B)

The #+ notation is a read-time condition, that reads the next form only if the conditional expression evaluates to true. Here the condition is the whole #+big-endian text which means that the test is satisfied if the :big-endian keyword belongs to the *FEATURES* list (a list which contains among other things platform-specific information). The following expression is 'B, which is either read or skipped according to the outcome of the test. If your platform is big-endian and you write the above form in the REPL, it is exactly as if you wrote the following:

CL-USER>(lambda()'L 'B)

(NB.CL-USER> is the prompt)

A function's body is an implicit PROGN, meaning that only the evaluation of the last expression is returned. So the above actually returns symbol ̀B. If however the read-time condition evaluates to false, the form reads as if you wrote:

CL-USER>(lambda()'L)

... which simply returns symbol L.

share|improve this answer
    
Snippets are not allowed; write full programs or functions instead. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ 14 hours ago
    
@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Updated, thanks – coredump 13 hours ago
    
Note: Snippets are only allowed if explicitly permitted by the OP. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ 13 hours ago

Julia, 24 19 bytes

()->ntoh(5)>>55+'B'

This is an anonymous function that takes no input and returns a Char. To call it, assign it to a variable. It assumes that integers are 64-bit.

The ntoh function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, ntoh is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so ntoh(5) == 360287970189639680. Which is also, perhaps more readably, equal to: 0000010100000000000000000000000000000000000000000000000000000000 in binary.

If we right bit shift the result of ntoh(5) by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant 'B', we'll get 'B' or 'L' for big or little endian machines, respectively.

Saved 5 bytes thanks to FryAmTheEggman and Dennis!

share|improve this answer
    
For 32 bit you would have to change 55 to 23 (also the 5 in the 16 bit one should have been 7, my mistake). I think Dennis meant something like: ()->ntoh(5)>>55+'B'? – FryAmTheEggman yesterday
1  
f()='L'-ntoh(10)%16 and f()='L'-ntoh(10)&10 should work on all platforms. – Dennis yesterday

Node, 42 bytes

n=>require('os').endianness()[0]

Pro: there's a builtin. Con: property names are very long

share|improve this answer

Perl 5, 21 + 1 = 22 bytes

Run with perl -E.

say ord pack(S,1)?L:B

Tested on amd64 (little-endian) and mips (big-endian).

share|improve this answer
    
Is the -E flag really necessary in the byte count? You can just say you use Perl 5.10 (since the saycommand is available in this version) – Paul Picard yesterday
1  
@PaulPicard But use 5.10.0; is many more bytes! – Anders Kaseorg yesterday
1  
@PaulPicard Your point is wrong. Perl 5.10 requires the -E switch or the use statement for say. – Anders Kaseorg yesterday
1  
-E is "free" on PPCG. No need to add anything. – ven 13 hours ago
1  
(however -n and -p are not) – ven 13 hours ago

Clojure, 46 44 bytes

#(nth(str(java.nio.ByteOrder/nativeOrder))0)

This is a function that uses the Java builtin to get the endianness of the machine. Then get the string representation of it which will be either "LITTLE_ENDIAN" or "BIG_ENDIAN" and take the first character of whichever string is chosen and return that.

Saved 2 bytes thanks to @cliffroot.

share|improve this answer
    
What is clojure really, is it lisp or java? – Leaky Nun yesterday
    
@LeakyNun Maybe a practical LISP that works with Java? It's hard to say. – miles yesterday
    
#(nth(str(java.nio.ByteOrder/nativeOrder))0) is 2 bytes shorter – cliffroot yesterday

C#, 60 52 bytes

C# is surprisingly competitive in this one.

char e=>System.BitConverter.IsLittleEndian?'L':'B';

Credits to Groo for the C#6 syntax.

60 bytes:

char e(){return System.BitConverter.IsLittleEndian?'L':'B';}
share|improve this answer
    
With C#6 syntax you can shorten it a bit: char e=>System.BitConverter.IsLittleEndian?'L':'B';, of course this (as well as the Java answer) doesn't actually print the value. – Groo yesterday
    
Welcome to Programming Puzzles & Code Golf! This is a nice first answer. – Alex A. 19 hours ago

PHP 5.6, 41 31 bytes (thx to isertusernamehere)

<?=unpack(S,"\x01\x00")[1]-1?B:L;

PHP 7, 41 bytes

echo unpack('S',"\x01\x00")[1]-1?'B':'L';

Idea stolen from: http://stackoverflow.com/a/24785578/2496717

share|improve this answer
    
You can save 10 bytes: <?=unpack(S,"\x01\x00")[1]-1?B:L;. – insertusernamehere yesterday

Ruby, 3130 chars.

puts [1].pack("s")>"\01"??L:?B

Hmm, must be a better way. Count 5 characters less if the char need not to be output as I think other solutions omit printing. i.e. remove the "puts " part if you don't want anything printed.

share|improve this answer
    
If I remember correctly, after Ruby 1.9, you can use ?L and ?B in place of puts :L and puts "B" – Sherlock9 yesterday
    
I think puts [76,66].pack("s")[0] will work. – Wayne Conrad yesterday
    
@Sherlock9, thanks, one char less. @WayneConrad, Perhaps add your answer, I don't have a big endian machine at hand to test but on little endian it works. But changing like this does not work: puts [76,66].pack("s>")[0]. That means it is possible to not be working on big endian for some reason I don't understand well. But this one seems to work (derived from your solution) puts [19522].pack("s>")[0]. WDYT? I wonder if I can find some place to evaluate on big endian. – akostadinov 18 hours ago
    
Alas, I also lack a big-endian machine to test on. – Wayne Conrad 9 hours ago

PowerShell, 44 bytes

[char](66+10*[BitConverter]::IsLittleEndian)

Character 66 is B, and 10 characters later is number 76, L. A Boolean value of "true" becomes 1 when cast to a number. BitConverter is a standard .NET class.

share|improve this answer

Dyalog APL, 28 bytes

'LB'⊃⍨'E'⎕FPROPS⎕D⎕FCREATE 0

⎕D⎕FCREATE 0 create an APL component file with the name 0123456789
'E'⎕FPROPS query endian-ness (0=little, 1=big)
'LB'⊃⍨ pick from the string

Requires ⎕IO←0, which is default on many systems.

share|improve this answer

Racket, 35 28 bytes

(if(system-big-endian?)'B'L)

'B or 'L respectively. Let me know if this is not specific enough :)

share|improve this answer

C, 34 bytes

This assumes ASCII character encoding

main(a){putchar(66+10**(char*)a);}

Call without argument.

Explanation:

On call, a will be 1. *(char*)a accesses the first byte of a, which on little-endian platforms will be 1, on big-endian platforms will be 0.

On big-endian platforms, this code will therefore pass 66 + 10*0 = 66 to putchar. 66 is the ASCII code for B. On little-endian platforms, it will pass 66 + 10*1 = 76, which is the ASCII code for L.

share|improve this answer

Kotlin, 42 bytes

{(""+java.nio.ByteOrder.nativeOrder())[0]}

Pretty straightforward. Uses "native" Java API. This is a lambda of () -> Char type.

String templates don't help much, unfortunately (still 42 bytes):

{"${java.nio.ByteOrder.nativeOrder()}"[0]}

Function approach (48 bytes):

fun e()=(""+java.nio.ByteOrder.nativeOrder())[0]
share|improve this answer

C, 27

One byte longer, but here it is anyway:

f(){putchar(htons(19522));}
share|improve this answer

PHP, 22 bytes

<?=ord(pack(S,1))?L:B;
share|improve this answer

Bash (and other unix shells), 32 (33) bytes

First and second attempt:

case `echo|od` in *5*)echo B;;*)echo L;;esac # portable
[[ `echo|od` =~ 5 ]]&&echo B||echo L         # non-portable

Thanks to Dennis, shorter version:

od<<<a|grep -q 5&&echo L||echo B  # non-portable
echo|od|grep -q 5&&echo B||echo L # portable

The echo utility outputs a newline, with hex value 0A, and no other output. For <<<a it is 61 0A.

The od utility, by default, interprets the input as two-byte words, zero-padded if the number of bytes is odd, and converts to octal. This results in the output of echo being interpred as 0A 00, which is converted to 005000 as big-endian or 000012 in little-endian. 61 0A becomes 005141 in little-endian and 060412 in big-endian. The full output of od also includes address and size data meaning we cannot use 0, 1, or 2 for the test.

The command is well-defined to expose the system's endianness. From the standard:

The byte order used when interpreting numeric values is implementation-defined, but shall correspond to the order in which a constant of the corresponding type is stored in memory on the system.

Compatibility notes

I am not certain if putting echo|od in backquotes with no double quotes around them [which results in a three-word argument to case] is supported on all systems. I am not certain if all systems support shell scripts with no terminating newline. I am mostly certain but not 100% of the behavior of od with adding the padding byte on big-endian systems. If needed, echo a can be used for the portable versions. All of the scripts work in bash, ksh, and zsh, and the portable ones work in dash.

share|improve this answer
    
None of the changes are necessary; just put one shell it works in in the language headet and you're set. – Dennis 3 hours ago
    
@Dennis I like doing that kind of analysis... though it's more fun if I do find something non-standard that gets a shorter answer in bash or zsh than the others. Maybe I'll see what can be done with [[ – Random832 3 hours ago
1  
Nothing wrong with the analysis. The last paragraph just sounded like you were uncertain if a shell-specific answer is valid... od<<<a|grep -q 5&&echo L||echo B should work in Bash and others. – Dennis 3 hours ago

Nim, 21 20 bytes

($cpuEndian)[0].echo

Takes the cpuEndian builtin (either littleEndian or bigEndian depending on the target CPU), stringifies it with $, takes its 0th character (l or b depending on the target CPU), and uses Nim's uniform function call syntax to echo the result.

share|improve this answer

Lua, 31 bytes

print(("H"):pack(19522):sub(2))

Lua 5.3 is required.

share|improve this answer

R, 28 23 bytes

substr(.Platform$endian,1,1)

.Platform$endian returns big if run on big endian and little if on little. Here, using substr, it returns the first letter of the output, so either b or l.

As endian is the only object starting with an e contained in object .Platform we can reduce it thanks to partial matching to the following 23 bytes code:

substr(.Platform$e,1,1)
share|improve this answer

VBA, 151 Bytes

Type x
q As Long
End Type
Type z
w As Integer
End Type
Sub q()
Dim i As x, y As z
y.w=1
LSet i=y
Debug.? IIf(i.q=1,"L","B")
End Sub
share|improve this answer

C# 50 bytes

Works, but has to be marked as unsafe

char i(){var a=0x0001;return*(byte*)&a>0?'L':'B';}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.