관리 메뉴

Kyung_Development

인코딩(encoding) 디코딩(decoding)을 써야 하는 이유 본문

IT 이야기

인코딩(encoding) 디코딩(decoding)을 써야 하는 이유

Kyung_Development 2024. 2. 19. 11:06

우선적으로 인코딩과 디코딩을 설명하자면

 

인코딩이란?

- 정보나 데이터를 특정 형식이나 규칙에 따라 변환하는 과정을 말합니다.

 

디코딩이란?

- 인코딩된 데이터나 정보를 다시 원래의 형식이나 내용으로 변환하는 과정을 말합니다.

 

 

이같은 인코딩, 디코딩을 하는이유는 다음과 같습니다.

  1. 데이터 보호: 암호화된 데이터를 전송하고자 할 때, 데이터를 인코딩하여 더 안전하게 보호할 수 있습니다. 디코딩은 이를 해독하는 과정을 의미합니다.
  2. 데이터 압축: 데이터를 압축하여 저장 공간을 절약하거나 네트워크 대역폭을 절약할 수 있습니다. 디코딩은 압축된 데이터를 다시 복원하는 과정을 의미합니다.
  3. 데이터 변환: 데이터를 한 형식에서 다른 형식으로 변환할 때 인코딩 및 디코딩이 사용됩니다. 예를 들어, 이미지를 텍스트로 변환하거나 텍스트를 음성으로 변환하는 것 등이 해당됩니다.
  4. 프로토콜 호환성: 서로 다른 시스템 간에 통신할 때, 데이터를 인코딩하여 프로토콜 간의 호환성을 유지할 수 있습니다.
  5. 오류 검출 및 수정: 특정 인코딩 방식을 사용하여 데이터를 전송하면, 디코딩 단계에서 오류를 감지하고 필요한 경우 수정할 수 있습니다.

이러한 이유들로, 인코딩과 디코딩은 데이터 통신 및 처리에서 중요한 역할을 합니다.

 

 

Android 인코딩( java )

import android.util.Base64;

String originalText = "Hello, World!";
byte[] data = originalText.getBytes("UTF-8");
String encodedText = Base64.encodeToString(data, Base64.DEFAULT);

 

 

Android 디코딩 ( java )

import android.util.Base64;

String encodedText = "SGVsbG8sIFdvcmxkIQ==";
byte[] decodedData = Base64.decode(encodedText, Base64.DEFAULT);
String decodedText = new String(decodedData, "UTF-8");

 

 

json인 경우 ( java )

import org.json.JSONException;
import org.json.JSONObject;

try {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("key", "value");
    String jsonString = jsonObject.toString();
    
    // JSON 데이터를 다시 JSONObject로 디코딩
    JSONObject decodedObject = new JSONObject(jsonString);
    String decodedValue = decodedObject.getString("key");
} catch (JSONException e) {
    e.printStackTrace();
}

 

 

 

Android 인코딩( kotlin )

import android.util.Base64
import java.nio.charset.StandardCharsets

val originalText = "Hello, World!"
val data = originalText.toByteArray(StandardCharsets.UTF_8)
val encodedText = Base64.encodeToString(data, Base64.DEFAULT)

 

 

Android 디코딩 ( kotlin )

import android.util.Base64
import java.nio.charset.StandardCharsets

val encodedText = "SGVsbG8sIFdvcmxkIQ=="
val decodedData = Base64.decode(encodedText, Base64.DEFAULT)
val decodedText = String(decodedData, StandardCharsets.UTF_8)

 

 

json인 경우 ( kotlin )

import org.json.JSONObject

fun main() {
    // JSON 객체 생성
    val jsonObject = JSONObject()
    
    // 데이터 추가
    jsonObject.put("name", "John")
    jsonObject.put("age", 30)
    jsonObject.put("isStudent", true)
    
    // JSON 객체를 문자열로 변환
    val jsonString = jsonObject.toString()
    println("JSON 문자열: $jsonString")
    
    // JSON 문자열을 다시 JSON 객체로 변환
    val newJsonObject = JSONObject(jsonString)
    
    // 데이터 읽기
    val name = newJsonObject.getString("name")
    val age = newJsonObject.getInt("age")
    val isStudent = newJsonObject.getBoolean("isStudent")
    
    // 결과 출력
    println("Name: $name, Age: $age, IsStudent: $isStudent")
}

 

 

html 인 경우

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Base64 Encoder/Decoder</title>
</head>
<body>
    <h1>Base64 Encoder/Decoder</h1>
    
    <label for="textInput">Enter Text:</label><br>
    <input type="text" id="textInput"><br><br>
    
    <button onclick="encodeText()">Encode</button>
    <button onclick="decodeText()">Decode</button><br><br>
    
    <label for="output">Output:</label><br>
    <textarea id="output" rows="4" cols="50"></textarea>
    
    <script>
        function encodeText() {
            var textInput = document.getElementById("textInput").value;
            var encodedText = btoa(textInput); // Encode text to Base64
            document.getElementById("output").value = encodedText;
        }
        
        function decodeText() {
            var encodedText = document.getElementById("output").value;
            var decodedText = atob(encodedText); // Decode Base64 to text
            document.getElementById("output").value = decodedText;
        }
    </script>
</body>
</html>

 

 

 

c# 인경우

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Base64 Encoder/Decoder");
        Console.WriteLine("----------------------");

        while (true)
        {
            Console.WriteLine("\n1. Encode\n2. Decode\n3. Exit");
            Console.Write("Select an option: ");
            int option = int.Parse(Console.ReadLine());

            switch (option)
            {
                case 1:
                    Console.Write("Enter text to encode: ");
                    string plainText = Console.ReadLine();
                    string encodedText = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(plainText));
                    Console.WriteLine("Encoded text: " + encodedText);
                    break;

                case 2:
                    Console.Write("Enter Base64 text to decode: ");
                    string base64Text = Console.ReadLine();
                    byte[] data = Convert.FromBase64String(base64Text);
                    string decodedText = System.Text.Encoding.UTF8.GetString(data);
                    Console.WriteLine("Decoded text: " + decodedText);
                    break;

                case 3:
                    Console.WriteLine("Exiting program...");
                    return;

                default:
                    Console.WriteLine("Invalid option! Please select again.");
                    break;
            }
        }
    }
}