화면 해상도를 알려주세요!


33

장치의 화면 해상도를 특정 형식 [width]x[height](괄호없이)으로 출력합니다. 예를 들어, 출력은입니다 1440x900.

다음은 자신의 화면 해상도를 확인하는 데 사용할 수있는 온라인 테스터입니다.


17
특정 출력 형식은 재미 있지 않지만 지금 변경하기에는 너무 늦었습니다.
Luis Mendo

3
여러 디스플레이가 연결된 경우 어떻게해야합니까?
Jonathan Allan

4
먼저 해상도를 변경 한 다음 해당 값을 알려줄 수 없습니다.
엔지니어 토스트

3
APL \ 360 (IBM / 360 타자기 환경에서만 실행할 수 있음), 5 바이트 :'0x0'
Adám

4
나는 이것이 골프 언어의 대부분을 박탈하고 사람들이 실제 언어의 한계를 탐구하도록 장려한다는 것을 좋아한다.
로비

답변:


38

자바 스크립트 (ES6), 32 바이트

(_=screen)=>_.width+"x"+_.height

함수로 출력합니다 return. f=시작 부분에 추가 하고처럼 호출하십시오 f(). 매개 변수 초기화를 사용하여 매개 변수 _screen오브젝트 로 초기화하십시오 . 나머지는 자명하다.

f=(_=screen)=>_.width+"x"+_.height
console.log(f())

참고 : 이 함수에 인수를 전달하면 실패합니다.


자바 스크립트 (이전 솔루션), 35 바이트

with(screen)alert(width+"x"+height)

내가 언젠가 사용할 것이라고 생각하지 않았습니다 with! 나는 이것이 더 골프를 칠 수 있다고 생각하지 않습니다.


REPL이 허용되면 s=screen,s.width+"x"+s.height(29 자)도 작동합니다.
Kobi

우우 기본 인수 값을 잘 사용합니다.
Matthew Roh

35 바이트 솔루션을 귀찮게하지 않음으로써 다섯 바이트를 저장할 수 있습니다 alert: with(screen)(width+'x'+height)단지 적절한 문자열을 반환합니다.
KRyan

2
이 답변은 근본적으로 결함이 있습니다. 브라우저를 확대하거나 축소하여 치트를 쓸 수 있습니다!
그레이트 오리

1
자, 너희들도 노력하고 있습니다 _=screen,_.width+"x"+_.height, 29 바이트
M28

33

TI-BASIC, 30 32 29 바이트 (비경쟁?)

* sigh * TI-BASIC은 모든 소문자에 대해 추가 바이트를 사용합니다.

@Timtech 덕분에 +2

@Timtech 덕분에 -3

:If ΔX>.1
:Then
:Disp "96x64
:Else
:Disp "320x240

TI-BASIC은 96 x 64 및 320 x 240의 두 가지 화면 해상도를 가진 계산기에서만 실행할 수 있기 때문에 작동합니다. 화면 해상도에 따라 다른 것으로 줌을 설정하여 어떤 화면이 있는지 확인합니다. 올바른 해상도를 출력합니다.

하드 코딩되어 있기 때문에 현재는 경쟁이 아닌 것으로 표시하고 있습니다.


6
영리한 학대;)
Matthew Roh

1
하나 이상의 바이트 ZDecimal를 사용 하지 않고 다른 Xmax비교 를 사용 하여 저장할 수 있습니다 . 또한 x1 바이트 대문자 대신 2 바이트 (x2) 인 소문자를 사용해야한다고 생각합니다 .
Timtech

@Timtech ZDecimal기본 줌 ( ZStandard)이 두 계산기에서 동일 하기 때문에 2 바이트 줌 (예 :)을 사용해야합니다 . 그래도 대문자를 수정하겠습니다.
Scott Milner

1
아 무슨 말인지 알 겠어 당신이 사용하는 경우 ZStandard, 그래도 것 ΔX계산기를 사이에 다음 다를 수? 또한 ZDecimal1 바이트이므로 31 바이트입니다.
Timtech

2
어떤 이유로, 나의 즉각적인 반응은 "유효하지만 화면 해상도가 하나만있는 경우에는 유효하지 않습니다"이지만 그 관점은 내부적으로 일치하지 않는 것 같습니다. 그래서 이것이 부정 행위인지 아닌지 확실하지 않습니다.

20

자바 스크립트 (ES6), 32 바이트

_=>(s=screen).width+'x'+s.height

console.log((_=>(s=screen).width+'x'+s.height)())


2
람다 버전은 허용됩니다
Felipe Nardi Batista

6
_=>(s=screen).width+'x'+s.height바이트 절약
Felipe Nardi Batista

@FelipeNardiBatista 고마워요, 생각도 나에게도 일어났습니다 :)
SethWhite

1
잘 했어! +1 :)
Arjun

5
모든 JS 항목이 다른 많은 답변보다 일관되게 짧은 방법을 좋아합니다. 거의 일어나지 않습니다.
Draco18s

11

macOS, bash, awk, grep, tr, 51 52 바이트

/*/*/sy*r SPDisplaysDataType|awk '/so/{print$2$3$4}'

를 실행 system_profiler하고 SPDisplaysDataType정보를 얻고 첫 번째 so를 검색 Resolution하여 화면 해상도를 인쇄합니다. 여러 화면의 경우 모든 해상도를 인쇄합니다.

Example of the command running.


이전의 호환되지 않는 변형 :

/*/*/sy*r SPDisplaysDataType|grep so|tr -d 'R :a-w'

방금 두 번째 디스플레이가 연결된 MacBook Pro에서 이것을 실행했습니다. 나는 2880x1800\n1920x1080@60Hz(두 줄)을 얻었다 . 그것이 자격을 박탈하는지 모르겠습니다 ... 또는?
Floris

@Floris는 여러 화면이있을 때 OP가 동작하는 방법을 지정 했습니까?
Captain Man

아니요-형식 @60Hz이 명확하지 않습니다.
Floris

|sed 1q바이트 수를 최대 58 바이트로 가져올 수 있다고 생각합니다 .
zgrep

나는 awk여분의 바이트 로 전환하고 비준수를 수정했습니다 . :)
zgrep


9

3, 37 바이트 처리

fullScreen();print(width+"x"+height);

fullScreen()앱이 최대 크기 (디스플레이 해상도)로 실행되도록합니다. 명백한 것보다 1 바이트 적음

print(displayWidth+"x"+displayHeight);

8

AutoHotKey, 34 바이트

SysGet,w,0
SysGet,h,1
Send,%w%x%h%

확장자가 .AHK 인 파일에 저장하고 명령 프롬프트에서 실행하십시오.


1
Send오히려 사용 하지 MsgBox않겠습니까?
엔지니어 토스트 14

@EngineerToast 감사합니다! 즉 두 바이트 저장
jmriego을

7

C (Windows), 79 78 77 바이트

바이트를 저장해 준 @Johan du Toit에게 감사합니다!

#import<windows.h>
#define G GetSystemMetrics
f(){printf("%dx%d",G(0),G(1));}

2
나는 당신의 대답을 볼 때까지 여전히 'GetDeviceCaps'를 어지럽히고있었습니다 :-) 다음을 사용하여 여전히 1 바이트를 절약 할 수 있습니다.#define G GetSystemMetrics f(){printf("%dx%d",G(0),G(1));}
Johan du Toit

7

PowerShell, 67 60 55 바이트

Martin Ender 에게 -7 감사합니다

Leaky Nun의 -5 (실제 12!) , Regex 마법사는 저쪽에 있습니다.

이것은 길지만 끔찍한 System.Windows.Forms.SystemInformation.PrimaryMonitorSize해결책 보다 길지 않습니다.

(gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"

먼저 Get-WmiObject( gwmi) 형식의 문자열 인 Win32_VideoController이라는 이름의 멤버가 포함 된 객체 를 검색 한 다음 정규식 바꾸기를 실행하여 올바른 형식을 얻습니다.VideoModeDescription1920 x 1080 x 4294967296 colors

PS H:\> (gwmi win32_videocontroller|% v*n)-replace" |x \d+\D+$"
1920x1080

(gwmi win32_videocontroller|% v*n)-replace" |x[^x]+$"정규식을 조정하여 몇 바이트를 면도 한다고 생각 합니다.
TessellatingHeckler

6

수학, 51 바이트

SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]~Infix~x

연결 한 장치에 따라 작동하지 않을 수 있습니다 (모름). 항상 작동해야합니다 (화면이 하나 이상 연결되어 있다고 가정).

Infix[Last/@("FullScreenArea"/.SystemInformation["Devices","ScreenInformation"][[1]]),x]

설명

SystemInformation[] 폼의 표현식을 반환

SystemInformationData[{
  "Kernel" -> {__},
  "FrontEnd" -> {__},
  "Links" -> {__},
  "Parallel" -> {__},
  "Devices" -> {__},
  "Network" -> {__},
}]

우리는에 관심이 있으며 "Devices", 직접 SystemInformation["Devices"]또는로 액세스 할 수 있습니다 SystemInformation[][[1,5,2]]. 결과는 양식의 목록이 될 것입니다

{
  "ScreenInformation" -> {__},
  "GraphicsDevices" -> {__},
  "ControllerDevices" -> {__}
}

우리는 원하는 "ScreenInformation"대로 SystemInformation["Devices","ScreenInformation"]또는 더 간결하게 액세스 할 수 있기를 원합니다 SystemInformation[][[1,5,2,1,2]]. 결과는 형식입니다

{
  {
  "ScreenArea" -> {__},
  "FullScreenArea" -> {{0,w_},{0,h_}},
  "BitDepth" -> _,
  "Resolution" -> _
  },
  ___
}

목록의 길이는 연결 한 화면 수입니다. 첫 번째 화면은 다음 SystemInformation[][[1,5,2,1,2,1]]과 같이 너비와 높이를 추출 할 수 있습니다. SystemInformation[][[1,5,2,1,2,1,2,2,;;,2]]그런 다음 Infix x출력 형식으로를 삽입하면 됩니다.


6

자바 7, 123114 바이트

String f(){java.awt.Dimension s=java.awt.Toolkit.getDefaultToolkit().getScreenSize();return s.width+"x"+s.height;}

이 메소드는 awt 라이브러리를 사용하기 때문에 TIO와 같은 헤드리스 Java 설치에서는 작동하지 않습니다. 기본적으로 호출 getScreenSize은 Java Native Interface를 사용하여 화면 너비 및 화면 높이를 호출합니다 (일반적으로 C 라이브러리로).

인쇄하는 대신 문자열을 반환 할 수 있음을 상기시켜 준 Olivier Grégoire 덕분에 -9 바이트 .


2
방금 게시하려고
Leaky Nun

@LeakyNun 당신과 나 둘 다. +1 찌르기 .
케빈 크루이 센

출력 제한이 너무 불량 ...x...때문에, void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll("[^\\d,]",""));}출력되는 1920,1200.. 짧은
케빈 Cruijssen

1
@KevinCruijssen 그래, 나도 그와 함께 연주를 시도했다. 실제 "너무 나쁘다"는 자바에서 정규식을 사용하는 것이 바이트 수 측면에서 너무 무겁다는 것입니다.
Poke 17

1
@Poke 당신은 정말로 맞습니다. 내가 사용 할 수 있었던 것을 내가 위에서 보여 무엇을 x대신 ,몇 가지 정규식 교체를 사용하여,하지만 현재 답이 5 바이트 더 : void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll("[^\\d,]","").replace(",","x"));}또는 void f(){System.out.print((java.awt.Toolkit.getDefaultToolkit().getScreenSize()+"").replaceAll(".*?(\\d+).*?(\\d+).*","$1x$2"));}자바 무거운없는 것을 잘 아 ..; P
케빈 Cruijssen

6

C #, 101 95 89 바이트

_=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};

OP가 인쇄에 대해 언급하지 않았 음 을 알려주@TheLethalCoder 덕분에 -6 바이트 덕분에 문자열 반환도 괜찮습니다. 그리고 람다로 변경하여 추가 -6 바이트.


당신은에 컴파일하여 11 바이트를 저장할 수 있습니다 Func<string>: ()=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};. 그러나 리턴 값이 void있지만 리턴 값을 리턴 string하려면 2 바이트를 추가해야합니다.
TheLethalCoder

1
도전 과제는 또한 입력을 할 수 없다는 것을 나타내지 않으므로 다른 바이트를 저장하기 위해 사용하지 않는 입력을 추가 할 수 있습니다._=>{var s=System.Windows.Forms.Screen.PrimaryScreen.Bounds;return s.Width+"x"+s.Height;};
TheLethalCoder

1
결과를 작성하는 반환 주석을 무시하십시오. 6 바이트를 반환하여 저장할 수 있습니다.
TheLethalCoder

And unless you can think of a way to get it shorter var s=System.Windows.Forms.Screen.AllScreens[0].Bounds; would also be the same count but you could golf it with that idea in mind.
TheLethalCoder

6

Bash + xrandr, 44 characters

read -aa<<<`xrandr`
echo ${a[7]}x${a[9]::-1}

xrandr belongs to the X server, on Ubuntu is provided by x11-xserver-utils package.

Sample run:

bash-4.3$ read -aa<<<`xrandr`;echo ${a[7]}x${a[9]::-1}
1920x1080

xrandr + grep + util-linux, 30 characters

xrandr|grep -oP '\d+x\d+'|line

Thanks to:

Sample run:

bash-4.3$ xrandr|grep -oP '\d+x\d+'|line
1920x1080

I have no bash with a display, would xrandr|grep * work?
Jonathan Allan

Sure. But for now the my grep and sed attempts to parse xrandr's output (pastebin.com/uTVcjWCq) were longer.
manatwork

Maybe xrandr|grep *|cut -d' ' -f1? (using the matching line from your paste @TIO)
Jonathan Allan

Ah, you mean to pick the resolution from the list by the “*” mark? Thought to that possibility, but I am not sure whether would work with multiple displays connected. As I remember, that would list each connected display's current resolution.
manatwork

Ah yes it would, not sure what the OP wants in such a scenario though!
Jonathan Allan

5

Python 2, 73 bytes

from ctypes import*
u=windll.user32.GetSystemMetrics;
print u(0),'x',u(1)

print u(0),'x',u(1) is smaller and his example (link) allows it
Felipe Nardi Batista

1
To clarify, If it's equivalent to the output from What is my screen resolution, It's valid. in that website, there is space between each part
Felipe Nardi Batista

@FelipeNardiBatista Updated, thanks.
Neil

5

Octave, 41 bytes

Thanks to @Arjun and @StephenS for corrections.

fprintf('%ix%i',get(0,'ScreenSize')(3:4))

0 is a handle to the root graphics object. Its property 'ScreenSize' contains the coordinates of the screen in pixels. The third and fourth entries give the desired information.


5

APL (Dyalog), 23 bytes

' 'R'x'⍕⌽⊃⎕WG'DevCaps'

⎕WG'DevCaps'Window Get Device Capabilities

 pick the first property (height, width)

 reverse

 format as text

' '⎕R'x'Replace spaces with "x"s


"substitute with an "x" at position 5 (the space)" this would cause problems on a small screen, e.g. 640x480 (which VMs use)
Baldrickk

4

Japt, 24 bytes

Ox`ØP(s×Çn)±d+"x"+ight

Test it online!

The compressed string represents with(screen)width+"x"+height. Ox evaluates this as JavaScript, and the result is implicitly printed.


4

C (SDL2 library) 113 88 84

(-4 chars due to @AppleShell 's help)

Yes. it compiles.

m[3];main(){SDL_Init(32);SDL_GetDesktopDisplayMode(0,m);printf("%dx%d",m[1],m[2]);}

Run with : gcc snippet.c -lSDL2 && ./a.out


3
I think you can shorten this by making m global and omitting int: m[3];main(){...
Appleshell

accessing by m+1 should be shorter than m[1] right? or isn't that possible in C but only in C++? surely printf has some dereference token
Gizmo

@gizmo unfortunately AFAIK there is no printf specifier that does such thing ..
dieter

4

Python 2, 61 49 bytes

Thanks @Jonathan-allan, @felipe-nardi-batista

from Tkinter import*
print'%sx%s'%Tk().maxsize()

For single display setups, this matches the output from the site. This gives entire resolution for multiple displays.


print'x'.... saves a byte
Felipe Nardi Batista

v=Tk().maxsize(), print'%sx%s'%v saves 9 bytes.
Jonathan Allan

oops, and then print'%sx%s'%Tk().maxsize() saves another 4 >_<
Jonathan Allan

3

bash + xdpyinfo 42 31 bytes

xdpyinfo|grep dim|cut -d' ' -f7

From man page:

xdpyinfo - is  a utility for displaying information about an X server.

@Floris @manatwork Thanks for saving a few bytes!


Crossed out 4 is still 4 :(
Christopher

There is no need for spaces around the pipes; I think is safe to search for “dim” only; you can write -d\ instead of -d' '. Then when it comes to both grep for a line and cut a part of that line, usually is shorter with a single awk call: xdpyinfo|awk '/dim/&&$0=$2'.
manatwork

I suspect you can grep something shorter than dimensions but I don't have xdpyinfo on my system...
Floris

3

xrandr + awk, 25 bytes

xrandr|awk /\*/{print\$1}

enter image description here


1
This doesn't work. grep * expands the asterisk to all files in the directory.
Jens

@Jens Corrected. Thanks for pointing out
Pandya

Thanks; another hint: the proper spelling for grep|cut is awk.
Jens

It still doesn't work. It outputs *0. My xrandr output is *0 3360 x 1050 ( 889mm x 278mm ) *0.
Jens

@Jens then you need -f2 Btw, Can you check xrandr|awk '/\*/{print $2}'?
Pandya

3

ZX Spectrum Basic, 10 bytes

just for completeness:

PRINT "256x192"

outputs 256x192. The Spectrum has a fixed hardwired screen resolution.


...and uses a single byte for keywords like PRINT.
Jens

2

Processing, 51 bytes

void setup(){fullScreen();print(width+"x"+height);}

This outputs in this format: width height. Also, the program creates a window that is the size of the screen you are using (because every Processing program creates a window by default) and this program just outputs the height and the width of this window/sketch.


Oh, the format is WIDTHxHEIGHT.
Matthew Roh

@SIGSEGV Just noticed it
Kritixi Lithos

2

xdpyinfo + awk, 28 bytes

$ xdpyinfo|awk /dim/{print\$2}
3360x1050

Tested on Cygwin with dual heads.


1
xdpyinfo|awk /dim/{print\$2} takes 28 bytes not 24
Pandya

@Pandya I need new glasses :-)
Jens


1

Lithp, 116 bytes

((import html-toolkit)
(htmlOnLoad #::((var S(index(getWindow)screen))
(print(+(index S width)"x"(index S height))))))

(Line breaks added for readability)

Try it online!

Finally, my html-toolkit module gets some use! Only works in the Try it Online link, will not work from command line.

A few bytes could be saved if 1024 x 768 could be valid output. We just use (+ .. "x" .. ) to avoid print's implicit spacing.


Hmm. I tried it online, but it says 2048x1080 for a true 4K screen that's actually 4096x2160. Any idea why? Firefox 52.0 on FreeBSD 11.
Jens

No idea. I'm merely grabbing window.screen and getting the width and height attributes from it. I imagine if you opened up the Firefox console and typed in window.screen you'll see the apparently incorrect 2048x1080.
Andrakis

1

Lua (löve framework),116 bytes

f,g=love.window.setFullscreen,love.graphics function love.draw()f(1)w,h=g.getDimensions()f(0>1)g.print(w.."x"..h)end

The programm changes first to fullscreen then it gets the width and height and prints it then :)


1

xrandr and sh, 23 bytes

$ set `xrandr`;echo $6x$8
3360x1050

Tested on a CentOS 5 box with display redirected to a Cygwin machine with two monitors. Here the full xrandr output is

$ xrandr
 SZ:    Pixels          Physical       Refresh
*0   3360 x 1050   ( 889mm x 278mm )  *0
Current rotation - normal
Current reflection - none
Rotations possible - normal
Reflections possible - none

1

Ruby + xrandr, 37 bytes

puts `xrandr`.split[7..9].join[0..-2]

Alternate solution (52 bytes):

puts `xrandr`.match(/t (\d+) (x) (\d+),/)[1..3].join

1

Red, 26 Bytes

system/view/screens/1/size

Outputs for example:

1920x1080

The code is pretty self explanatory. The 1 refers to the first screen

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.