RGB值转换为数组 [英] RGB value convert to in array

查看:151
本文介绍了RGB值转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些RGB颜色值,比如#e03cec,我想把它变成int数组,我需要一些帮助。

我写了这样的代码:

I have some RGB color value like #e03cec and I want to make it to int array ,I need some help.
I have write code like this:

public static int [] TestInt(String rgbColor)
{
    String rgb = rgbColor.substring(1, rgbColor.length());
    String [] Hex= new String [3];
    int [] IntRgb =new int [3];
    for(int i=0;i<3;i++)
    {
      Hex[i]=rgb.substring(2*i,2*i+2);
      IntRgb[i]=Integer.parseInt(Hex[i],16);
    }
    return IntRgb;
}



但是我无法确定它是否正确。


but I can not make sure whether it is right.

推荐答案

它是其实很容易检查。写一个测试:)





所以,你想测试你的方法是否正确地将输入RGB字符串转换为3元素整数数组。



您给出的顺序应分为以下三个元素



R = e0,其中是0xe0

G = 3c,即0x3c

B = ec,即0xec



所以要测试,我会说你使用像 junit 这样的单元测试框架,但下面是一个快速而肮脏的测试片段,用于解释原理。 />


It is actually very easy to check. Write a test :)


So, you want to test if your method correctly converts the input RGB string into a 3 element integer array.

The sequence you gave should be split into the following three elements

R = e0, which is 0xe0
G = 3c, which is 0x3c
B = ec, which is 0xec

So to test, I would sucggest you use a unit testing framework like junit, but below is a quick and dirty test snippet, to explain the principle.

int[] result = TestInt("#e03cec");

// So because it is integer value, you can compare the hex values
// expected to the array
if (result[0] != 0xe0) throw new RuntimeException("Error");
if (result[1] != 0x3c) throw new RuntimeException("Error");
if (result[2] != 0xec) throw new RuntimeException("Error");

// (or if you are really paranoid you can use
// a calculator to convert the hex to base 10 (int) which would be
// 224, 60 and 236
if (result[0] != 224) throw new RuntimeException("Error");
if (result[1] != 60) throw new RuntimeException("Error");
if (result[2] != 236) throw new RuntimeException("Error");

System.out.println("OK");


这篇关于RGB值转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆